Passing data from Puppeteer to Vue JS Component

110 Views Asked by At

The data flow of my app begins with a backend API request which launches a Vue component using puppeteer. Is there any way I can pass that data from Backend (express) to the vue component which is launched other than making the Vue component call a backend API to fetch data?

I have tried calling a backend API from the launched component but this seems to be a work-around rather than an actual solution.

1

There are 1 best solutions below

0
shadowyfour On

Functions added to the window object through puppeteer's exposeFunction method can be called from within a Vue component to retrieve data from the backend.

For example, the puppeteer code (in an example where the backend API request contained the data myData):

const page = await browser.newPage();
await page.exposeFunction('getRequestData', () => myData);
await page.goto("http://localhost/")

And the code you would put in Vue, to be executed when the component is mounted:

this.data = await window.getRequestData();

Or if you need to get the types to compile in typescript:

this.data = await (window as unknown as { getRequestData: () => Promise<myDataType> }).getRequestData();

Another way to pass information from puppeteer to vue.js is through custom events and event listeners

For example, using vue3's composition syntax, the js part of a vue SFC could look like:

const myData = ref<MyDataObject>()

window.addEventListener('custom:data', e => {
  myData.value = (e as CustomEvent).detail;
})

I believe this correlates to the following in vue2, although I'm unable to test this at the moment:

...
data: {
  myData: undefined
}
...
mounted: function() {
  window.addEventListener('custom:data',e => {
    this.myData = (e as CustomEvent).detail;
  });
},
...

On the puppeteer side of things, send the event using the evaluate method:

const myData = {} // data that express got from the initial backend API request
const page = await browser.newPage();
// any other configuration you need to do
await page.evaluate((data) => {
window.dispatchEvent(new CustomEvent('custom:data', {detail: data}));
}, myData)