Last active
February 10, 2025 19:40
-
-
Save john-doherty/12c3e2951ea875e5d51a7e66c6dd423e to your computer and use it in GitHub Desktop.
puppeteer wait for an event to fire
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Wait for the browser to fire an event (including custom events) | |
* @param {object} puppeteerPage - puppeteer page | |
* @param {string} eventName - Event name | |
* @param {integer} [seconds] - number of seconds to wait (default=30) | |
* @returns {Promise<object>} resolves when event fires or timeout is reached | |
*/ | |
async function waitForEvent(puppeteerPage, 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 | |
puppeteerPage.evaluate(function(eventName) { | |
return new Promise(function(resolve, reject) { | |
window.addEventListener(eventName, function(e) { | |
// resolves when the event fires | |
resolve({ | |
type: e.type, | |
detail: e.detail, | |
timeStamp: e.timeStamp | |
}); | |
}); | |
}); | |
}, eventName), | |
// if the event does not fire within n seconds, exit | |
new Promise(function(resolve) { | |
setTimeout(resolve, seconds * 1000); | |
}) | |
]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment