How to listen to postMessage messages in Puppeteer?

半腔热情 提交于 2019-12-24 01:43:32

问题


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 postMessages 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!