Skip to content

Instantly share code, notes, and snippets.

@john-doherty
Last active March 28, 2023 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save john-doherty/12c3e2951ea875e5d51a7e66c6dd423e to your computer and use it in GitHub Desktop.
Save john-doherty/12c3e2951ea875e5d51a7e66c6dd423e to your computer and use it in GitHub Desktop.
puppeteer wait for an event to fire
/**
* Wait for the browser to fire an event (including custom events)
* @param {string} eventName - Event name
* @param {integer} seconds - number of seconds to wait.
* @returns {Promise} resolves when event fires or timeout is reached
*/
async function waitForEvent(eventName, seconds) {
seconds = seconds || 30;
// use race to implement a timeout
return Promise.race([
// add event listener and wait for event to fire before returning
page.evaluate(function(eventName) {
return new Promise(function(resolve, reject) {
document.addEventListener(eventName, function(e) {
resolve(); // resolves when the event fires
});
});
}, eventName),
// if the event does not fire within n seconds, exit
page.waitFor(seconds * 1000)
]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment