是否可以监听页面内对象派发的事件?假设我在要访问的页面中有这段代码:
var event = new CustomEvent('status', { detail: 'ok' });
window.addEventListener('status', function(e) {
console.log('status: ', e.detail);
});
setInterval(window.dispatchEvent, 1000, event);
我希望能够监听由窗口对象(或与此相关的任何其他 JS 对象)分派(dispatch)的事件。我如何在 Puppeteer 中执行此操作?
最佳答案
首先,您必须公开一个可以从页面内调用的函数。其次,您监听事件并调用公开的函数并传递事件数据。
// Expose a handler to the page
await page.exposeFunction('onCustomEvent', ({ type, detail }) => {
console.log(`Event fired: ${type}, detail: ${detail}`);
});
// listen for events of type 'status' and
// pass 'type' and 'detail' attributes to our exposed function
await page.evaluateOnNewDocument(() => {
window.addEventListener('status', ({ type, detail }) => {
window.onCustomEvent({ type, detail });
});
});
await page.goto(/* ... */);
如果现在页面中触发了一个事件status
(就像您提供的代码),您会看到它被记录在您的 Node.js 应用程序的控制台中。
如评论中所述,可以在 puppeteer examples 中找到更复杂的示例.
关于javascript - Puppeteer:如何监听对象事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47107465/