google 开发人员的 Puppeteer 代码是否有问题:custom-event.js?

Are google devs just wrong with their Puppeteer code: custom-event.js?

当我在 https://try-puppeteer.appspot.com/ 上尝试自定义-event.js 时,日志中没有显示任何响应。当然可以通过显示代码的一些结果来改进此演示 运行 ?!?

我在 Puppeteer: How to listen to object events and the much less appreciated 上看到了热门答案(0 票!)。

NONE 第一个示例适用于 try-puppeteer,第二个示例适用!

我明白了,

First, you have to expose a function that can be called from within the page. Second, you listen for the event and call the exposed function and pass on the event data.

-- 但该代码段对 https://www.chromestatus.com/features 自定义事件不起作用(对我而言)。

使用 puppeteer 观察自定义事件的底线是什么?

前两个示例与最后一个示例有所不同:前两个示例仅说明了对事件的订阅,但它们并未触发此事件,因此那里没有可观察到的反应(这可能会造成混淆因为 reader 希望网站触发事件,但他们没有)。第三个示例确实触发了事件。

如果您相应地添加此行,即使在 https://try-puppeteer.appspot.com/ 上也可以获得前两个示例。

await page.evaluate(() => { document.dispatchEvent(new Event('app-ready')); });
await page.evaluate(() => { document.dispatchEvent(new Event('status')); });

好了,破解了,这样Puppeteer就可以检测到单个或者多个事件了。关于 puppeteer 的工作原理,有几件事对我来说并不明显:

  • puppeteer 页面 一个浏览器选项卡
  • 那个js可以附加到那个'tab'
  • puppeteer 必须在 'tab' 设置后浏览测试 url(时间很关键)

所以现在结合以前的答案,在 Node 或 try-puppeteer:

// in node wrap with an asynch iife 

const browser = await puppeteer.launch();
const page = await browser.newPage();
 
// 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('https://puppet.azurewebsites.net/puppeteer/soEvntSingle.html');

// await page.goto('https://puppet.azurewebsites.net/puppeteer/soEvnt.html');

// await page.waitFor(3000);
 
await browser.close();

检测从该网页触发的事件。在使用 devTools 的地方,您会看到事件是由 CustomEvent 触发的。

<script>

var event = new CustomEvent('status', { detail: 'ok' });
      
window.addEventListener('status', function(e) {
  console.log('status: ', e.detail);
});

window.dispatchEvent(event);

// setTimeout(window.dispatchEvent, 1000, event);
    
</script>

切换注释行并注释掉相应的行会让 Puppeteer 监视事件的重复触发。然后页面 soEvnt.html 每隔一秒就会触发 CustomEvent 'status' 事件。 Puppeteer 测试必须在某个阶段终止,以向终端(或 Jest 等测试基础设施)报告,因此监控设置为 3 秒。

!Google你可以随时来找我帮忙!