I’m working with Puppeteer and need to monitor custom events that happen inside the webpage. For example, if my target page has JavaScript code like this:
Is there a way to catch these custom events from my Puppeteer script? I want to listen for events that are triggered by the window object or other JavaScript objects on the page. What’s the best approach to handle this?
Use page.evaluateOnNewDocument() to inject event listeners before the page loads. This approach is effective for catching early-firing events, especially custom ones. For instance, you can set up a listener for the ‘alert’ event as follows:
This method helps ensure you do not miss any events and provides better control over the timing compared to using page.exposeFunction(), which can lead to race conditions with rapidly firing events.
You can also use page.evaluate() with promises to handle custom events in real-time. I’ve found this really useful when you need to wait for specific events during page interactions.
const eventPromise = page.evaluate(() => {
return new Promise((resolve) => {
window.addEventListener('alert', (event) => {
resolve({
eventType: event.type,
detail: event.detail,
timestamp: Date.now()
});
}, { once: true });
});
});
// Trigger some action that causes the event
await page.click('#some-button');
// Wait for the custom event
const eventData = await eventPromise;
console.log('Caught custom event:', eventData);
This works great when you know roughly when the event should fire and want to sync your Puppeteer script with specific custom events. The big advantage is it blocks execution until the event happens, so you can easily coordinate what happens next based on the event data.