When using puppeteer, functions can be added to the window
object using the exposeFunction
method. These functions can then be called from within a Vue component to retrieve data from the backend.
For instance, in a scenario where the backend API request returns the data myData
, you would include the following puppeteer code:
const page = await browser.newPage();
await page.exposeFunction('getRequestData', () => myData);
await page.goto("http://localhost/")
In the Vue component, you can execute the following code when the component is mounted:
this.data = await window.getRequestData();
If you require type definition for TypeScript compilation, you can use the following code snippet:
this.data = await (window as unknown as { getRequestData: () => Promise<myDataType> }).getRequestData();
Another approach to transmit information from puppeteer to vue.js involves utilizing custom events and event listeners.
For example, with vue3's composition syntax, the JavaScript segment of a Vue Single File Component could appear as follows:
const myData = ref<MyDataObject>()
window.addEventListener('custom:data', e => {
myData.value = (e as CustomEvent).detail;
})
A similar implementation in vue2 might resemble this:
...
data: {
myData: undefined
}
...
mounted: function() {
window.addEventListener('custom:data',e => {
this.myData = (e as CustomEvent).detail;
});
},
...
To trigger the event on the puppeteer side, use the evaluate method like so:
const myData = {} // data retrieved from the initial backend API request
const page = await browser.newPage();
// any other configuration required
await page.evaluate((data) => {
window.dispatchEvent(new CustomEvent('custom:data', {detail: data}));
}, myData)