custom-event.js (1001B)
1 /** 2 * @license 3 * Copyright 2017 Google Inc. 4 * SPDX-License-Identifier: Apache-2.0 5 */ 6 7 'use strict'; 8 9 const puppeteer = require('puppeteer'); 10 11 (async () => { 12 const browser = await puppeteer.launch(); 13 const page = await browser.newPage(); 14 15 // Define a window.onCustomEvent function on the page. 16 await page.exposeFunction('onCustomEvent', e => { 17 console.log(`${e.type} fired`, e.detail || ''); 18 }); 19 20 /** 21 * Attach an event listener to page to capture a custom event on page load/navigation. 22 * @param {string} type Event name. 23 * @returns {!Promise} 24 */ 25 function listenFor(type) { 26 return page.evaluateOnNewDocument(type => { 27 document.addEventListener(type, e => { 28 window.onCustomEvent({type, detail: e.detail}); 29 }); 30 }, type); 31 } 32 33 await listenFor('app-ready'); // Listen for "app-ready" custom event on page load. 34 35 await page.goto('https://www.chromestatus.com/features', { 36 waitUntil: 'networkidle0', 37 }); 38 39 await browser.close(); 40 })();