问题
https://github.com/GoogleChrome/puppeteer/blob/master/examples/custom-event.js shows how to define your own event, but doesn't show how to transmit event data back to the code outside Puppeteer.
For example, if I want to read event data the page postMessage
s in code using Puppeteer to launch the page, how would you do that?
Related: https://github.com/GoogleChrome/puppeteer/issues/2366
回答1:
I just bumped into the same problem and below is something that worked for me.
Using the same example from the Puppeteer library with some modifications.
'use strict';
const puppeteer = require('puppeteer');
(async() => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
let msgCollection = [];
// Define a window.onMessageReceivedEvent function on the page.
await page.exposeFunction('onMessageReceivedEvent', e => {
console.log(`${e.type} fired`, e.data || '');
msgCollection.push(e.data);
});
/**
* Attach an event listener to page to capture a custom event on page load/navigation.
* @param {string} type Event name.
* @return {!Promise}
*/
function listenFor(type) {
return page.evaluateOnNewDocument(type => {
window.addEventListener(type, e => {
window.onMessageReceivedEvent({type, data: e.data});
});
}, type);
}
await listenFor("message"); // Listen for "message" custom event on page load.
await page.goto('https://jsfiddle.net/sa1nd0w5/', {waitUntil: 'networkidle0'});
await browser.close();
// Do something with the collected data
console.log(msgCollection);
})();
来源:https://stackoverflow.com/questions/49808578/how-to-listen-to-postmessage-messages-in-puppeteer