Zimt

How to Click Cookie Popups in Playwright

· 4 min read · Cookies and Bars

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Clicking cookie popups and modal alerts in Playwright is a common automation task that ensures your tests run without interruptions. This guide shows you how to reliably locate, interact with, and dismiss these elements using Playwright's built-in features, including auto-waiting, locators, and dialog handling. You'll need a basic setup with Playwright installed and a test script ready.

What You'll Need

  • Node.js (or Python) environment with Playwright installed (via npm install @playwright/test or pip install playwright)
  • A test script or project where you can write and run Playwright code
  • Basic understanding of CSS selectors or accessible roles

Step-by-Step

  1. Identify the popup or modal element. Open your target website in a browser, inspect the cookie banner or modal using DevTools (right-click → Inspect). Note the button text (e.g., "Accept All"), its CSS selector (like #cookie-accept), or its accessible role (e.g., button with name "Accept").
  2. Use Playwright's auto-waiting. Playwright automatically waits for elements to be visible and actionable. For a cookie button with text "Accept All", use: await page.getByRole('button', { name: 'Accept All' }).click(); or await page.locator('#cookie-accept').click();. This handles most timing issues.
  3. Handle iframes if needed. Some cookie popups appear inside an iframe. Use const frame = page.frameLocator('iframe[src*="cookie"]'); then click the button within that frame: await frame.getByRole('button', { name: 'Accept' }).click();.
  4. Dismiss modal alerts (JavaScript dialogs). For native browser alerts (like alert() or confirm()), use Playwright's page.on('dialog') event. Add this before the action that triggers the dialog: page.on('dialog', dialog => dialog.accept());. This automatically clicks OK. For dismissal, use dialog.dismiss().
  5. Handle cookie banners that appear after page load. If the popup appears after a delay, use await page.waitForSelector('#cookie-banner', { state: 'visible' }); before clicking, or rely on Playwright's auto-wait for the click itself.
  6. Use fallback locators. Some sites have multiple cookie buttons (e.g., "Accept", "Reject"). Use a locator that matches the first visible one: const acceptButton = page.locator('button:has-text("Accept")').first(); then await acceptButton.click();.
  7. Test with multiple browsers. Run your script against Chromium, Firefox, and WebKit to ensure your locator works across browsers. Playwright makes this easy via projects in the config file.

Common Mistakes

  • Using page.click() without a valid selector – always verify the selector matches a unique element.
  • Forgetting that iframes require frame locators – clicking directly on a selector inside an iframe will fail.
  • Assuming the popup appears immediately – missing auto-wait can cause flaky tests if you don't wait for the element.
  • Handling dialogs incorrectly – if you don't register the dialog event listener before the dialog triggers, Playwright will throw an error.
  • Clicking a hidden element – Playwright auto-waits for visibility, but if the element is in a shadow DOM, you need to pierce it (see Tips).

Tips

  • Prefer role-based locators (getByRole) over CSS selectors because they are more resilient to class changes.
  • Use page.locator('text=Accept All') as a fallback if role doesn't match, but be careful of multiple matches.
  • For shadow DOM, use page.locator('css=selector').click() with the css= prefix, or use page.locator('your-selector').click() which automatically pierces open shadow roots in Playwright.
  • If a popup blocks the page, consider using await page.addStyleTag({ content: '.cookie-banner { display: none !important; }' }); to hide it, but only for testing, not for production.
  • Set a default timeout in your config (e.g., timeout: 10000) to avoid long waits.

Troubleshooting

  • Element not found: Check if the popup is inside an iframe or shadow DOM. Use page.locator('body').innerHTML() to inspect the page source at runtime.
  • Click intercepted: The button may be covered by another element. Use await locator.click({ force: true }) to bypass actionability checks, but first verify it's the right element.
  • Dialog not handled: Ensure you register page.on('dialog') before the action that triggers the dialog. If you miss it, Playwright will throw an error like "Dialog was not handled".
  • Popup appears after navigation: If the popup shows on a new page load, put the click logic after await page.goto() and use waitForSelector.
  • Multiple popups: Some sites show multiple popups sequentially. Loop through them with a while loop checking for visibility, but be cautious of infinite loops – set a max iteration count.

Frequently Asked Questions

How do I click a button inside a shadow DOM?

Playwright's locators automatically pierce open shadow roots. Just use a normal CSS selector, like page.locator('my-element .cookie-accept'). If it doesn't work, try page.locator('css=my-element .cookie-accept').

What if the cookie popup appears after a delay?

Playwright's auto-wait handles this. The click() method will wait for the element to be visible and actionable. You can also use page.waitForSelector() to explicitly wait.

How do I handle a popup that appears in a new tab?

Use const [newPage] = await Promise.all([page.waitForEvent('popup'), page.click('button')]); to capture the new tab, then interact with it like a normal page.

Can I bypass cookie popups entirely?

Yes, you can use page.addInitScript() to override window.alert or window.confirm to auto-accept, or inject CSS to hide the popup. But it's better to test the actual user flow by clicking the popup.

Why does my click work in one browser but not another?

Different browsers may render elements differently. Use role-based locators and test across browsers. Also, check if the element is only visible on certain viewport sizes – you can set the viewport in your test.

How do I dismiss a cookie banner without clicking a button?

Some banners close on pressing Escape. Use await page.keyboard.press('Escape'). If that doesn't work, click the close icon (often an "X" button) using its aria-label or CSS class.