How can I handle pop-ups and alerts using Playwright?

Playwright is a Node.js library to automate web browsers, which provides a high-level API to control headless or non-headless browsers. Handling pop-ups and alerts in Playwright is quite straightforward.

Handling JavaScript Alerts

JavaScript alerts are modal pop-ups that prevent the user from interacting with the rest of the web page until they are dismissed. In Playwright, you can handle this using the page.on('dialog', ...) event handler, which is emitted when a JavaScript dialog appears, such as alert, prompt, confirm or beforeunload.

Here is how you can handle it in JavaScript:

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();
  page.on('dialog', async dialog => {
    console.log(dialog.message());
    await dialog.dismiss();
  });
  await page.evaluate(() => alert('Alert!'));
  await browser.close();
})();

In the above code, we're setting up an event handler for the 'dialog' event. When a dialog (alert, prompt, confirm, or beforeunload) is triggered on the page, we simply log the dialog message and dismiss it.

Handling Popup Windows

For handling new popup windows, Playwright provides page.waitForEvent('popup') method that waits for the popup event and returns the popup page.

Here's how to handle popup windows:

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();
  const [popup] = await Promise.all([
    page.waitForEvent('popup'),
    page.evaluate(() => window.open('https://example.com'))
  ]);
  console.log(await popup.url());
  await browser.close();
})();

In the above code, we're using page.waitForEvent('popup') to wait for the popup to appear when we open a new window using window.open. It returns the new popup page that we can interact with.

Remember, Playwright treats a new tab in the same browser window as a new page, not a popup. The 'popup' event is only emitted when a new browser window is opened.

Always ensure that you are using up-to-date versions of Playwright and the browsers you are automating, as handling dialogs and popups can be affected by changes in the way these features are implemented in the browsers themselves.

Related Questions

Get Started Now

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