如何在Puppeteer中收听postMessage消息?

时间:2018-04-13 02:51:53

标签: google-chrome events message postmessage puppeteer

https://github.com/GoogleChrome/puppeteer/blob/master/examples/custom-event.js显示了如何定义自己的事件,但没有显示如何将事件数据传回给Puppeteer外部的代码。

例如,如果我想使用Puppeteer在代码中读取页面postMessage的事件数据来启动页面,那么你会怎么做?

相关:https://github.com/GoogleChrome/puppeteer/issues/2366

1 个答案:

答案 0 :(得分:1)

我只是遇到了同样的问题,下面是对我有用的东西。

example库中使用相同的Puppeteer,并进行了一些修改。

'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);

})();