How to handle browser events in Puppeteer?

To handle browser events in Puppeteer, you can use Puppeteer's event-driven architecture to listen to and handle various events. Puppeteer's page and browser objects both emit events that you can subscribe to.

Here is a list of some useful events:

  • console: Emitted when the page's console is called.
  • dialog: Emitted when a JavaScript dialog appears, such as alert, prompt, confirm or beforeunload.
  • request: Emitted when a request is issued by the page.
  • response: Emitted when a response is received.
  • error: Emitted when there is an uncaught exception within the page.
  • close: Emitted when the browser is closed.

Here is an example of how to handle some of these events:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  // listening to console event
  page.on('console', consoleObj => console.log(consoleObj.text()));

  // listening to dialog event
  page.on('dialog', async dialog => {
    console.log(dialog.message());
    await dialog.dismiss();
  });

  // listening to request event
  page.on('request', request => console.log('Request: ', request.url()));

  // listening to response event
  page.on('response', response => console.log('Response: ', response.url()));

  // navigate to a page
  await page.goto('https://example.com');

  await browser.close();
})();

In this example, we are handling console, dialog, request, and response events. When these events occur, the associated handler function is executed.

Remember to add these event listeners before navigating to the page with page.goto(), otherwise they won't be triggered for the initial page load.

In the console event, we're logging the console output from the page to the node.js console.

In the dialog event, we're logging the message of the dialog and then dismissing it.

In the request and response events, we're logging the URL of the request and the response. This can be very useful for debugging the network activity of a page.

Keep in mind that Puppeteer's event-driven nature is very powerful and allows you to handle many more situations in a customizable way.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon