Zimt

How to Handle GDPR Cookie Popups in Playwright

· 6 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

To handle GDPR cookie popups in Playwright, you need to locate the popup's accept button (or reject button) and click it, preferably before interacting with the rest of the page. The most reliable approach is to use Playwright's built-in waiting and actionability checks, combined with a robust selector that targets the button regardless of its exact text. This guide walks you through the process, from identifying the popup to writing reusable code that works across multiple pages and tests.

What You'll Need

  • A Node.js project with Playwright installed (npm init playwright@latest or npm install @playwright/test)
  • A basic understanding of Playwright's page object and locators
  • Access to a website that shows a GDPR cookie popup (most EU-based sites do)
  • Optionally, a browser extension or DevTools to inspect the popup's DOM structure

Step-by-Step

  1. Inspect the popup's DOM. Open the site in a regular browser, right-click the accept button, and select "Inspect." Note the button's id, class, data-* attributes, or its text content. For example, the button might be <button id="accept-cookies">Accept All</button>.
  2. Write a locator that is specific but resilient. Prefer a text-based locator if the button text is unique, e.g., page.getByRole('button', { name: 'Accept all' }) or page.getByText('Accept', { exact: true }). If the text varies (e.g., "Accept Cookies" vs "I Agree"), use a CSS selector like #accept-cookies or [data-testid="cookie-accept"]. Avoid overly broad selectors like button which could match multiple elements.
  3. Wait for the popup to appear. Use await page.waitForSelector('#accept-cookies', { state: 'visible' }) or rely on Playwright's auto-waiting by directly calling click() on the locator—Playwright will wait for the element to be attached, visible, and stable before clicking.
  4. Click the button. If you have a locator, do await page.getByRole('button', { name: 'Accept all' }).click(). If you used waitForSelector, you can then do await page.click('#accept-cookies').
  5. Handle the popup if it appears inside an iframe. Some cookie banners are in an iframe. You need to switch to that frame first: const frame = page.frameLocator('#cookie-iframe') then await frame.getByRole('button', { name: 'Accept' }).click().
  6. Make your code reusable. Create a helper function like async function acceptCookies(page) { ... } and call it at the start of each test, right after page.goto(). Alternatively, use a Playwright fixture or a global setup that runs once per session, but be aware some sites show the popup on every page load.
  7. Handle popups that appear after a delay or on scroll. If the popup shows after a few seconds, use await page.waitForSelector('#accept-cookies', { timeout: 5000 }) before clicking. If it appears on scroll, scroll down first, then wait.
  8. Test both accept and reject paths. GDPR requires giving users a choice. Write tests that click "Reject" or "Manage Preferences" to ensure your site works in both cases. Use the same locator strategy for those buttons.
  9. Verify the popup is gone. After clicking, assert that the popup is hidden or removed: await expect(page.locator('#cookie-banner')).toBeHidden(). This ensures the click actually worked.

Common Mistakes

  • Using a hard-coded wait like page.waitForTimeout(2000)—this is flaky and slows down tests. Use Playwright's auto-waiting instead.
  • Clicking before the popup is ready. If you click too early, Playwright might throw a timeout or click the wrong element. Always wait for the specific button.
  • Using a selector that matches multiple elements. For example, button or .accept might match both the accept and reject buttons. Use :text("Accept") or a unique ID.
  • Forgetting about iframes. If the popup is in an iframe, a normal locator won't find it. You must use frameLocator.
  • Assuming the popup appears on every page. Some sites only show it once per session. If your test navigates to multiple pages, you may need to check for the popup's presence before clicking, using a conditional.

Tips

  • Use page.addInitScript to block the popup entirely. You can inject a script that removes the cookie banner element as soon as the DOM is ready. For example: await page.addInitScript(() => { document.querySelector('#cookie-banner')?.remove(); }). This is faster but less realistic—use it only if you don't care about testing the popup itself.
  • Store the cookie consent in the browser context. After accepting, save the storage state with context.storageState() and reuse it in later tests to skip the popup. This is efficient for large test suites.
  • Use a data-testid attribute if you control the site's code. It's the most stable selector.
  • Run tests in headed mode (headless: false) when debugging to see the popup and confirm the click works visually.
  • Group all cookie handling in a single fixture so you don't repeat the same code in every test.

Troubleshooting

  • Playwright cannot find the button. Check if the popup is in an iframe. Also, the popup might be rendered after a network request—increase the timeout or use waitForSelector with a longer timeout. Inspect the current DOM with console.log(await page.content()) to see what's actually there.
  • The click times out even though the button is visible. This usually means the button is covered by another element or is not clickable (e.g., disabled). Use locator.click({ force: true }) only as a last resort, but first check if there's an overlay. Also, try locator.scrollIntoViewIfNeeded() before clicking.
  • The popup reappears on the next page. Some sites set a cookie only after a few seconds. Make sure you wait for the cookie to be set before navigating. Alternatively, your test might be using a new context each time—reuse the same context or save storage state.
  • The popup appears randomly. Use a conditional check: const banner = page.locator('#cookie-banner'); if (await banner.isVisible()) { await banner.getByRole('button', { name: 'Accept' }).click(); }. This avoids errors when the popup doesn't show.
  • Selectors work in the browser but not in Playwright. This often happens due to timing. Use page.waitForSelector with a visible state, and ensure you're not using a CSS selector that relies on pseudo-classes like :hover.

Frequently Asked Questions

Can I skip the cookie popup entirely?

Yes, you can use page.addInitScript to remove the popup element before it renders, or use a persistent context with a saved storage state that already has consent.

What if the popup has multiple buttons like "Accept All" and "Reject All"?

Use specific locators for each button, e.g., getByRole('button', { name: 'Accept All' }) and getByRole('button', { name: 'Reject All' }). Test both paths.

How do I handle a popup that appears in a shadow DOM?

Playwright supports piercing shadow DOM by default. Just use a normal locator like page.locator('my-element').getByRole('button') and it should work.

Is it better to block the popup or click it?

It depends on your test goals. For most tests, clicking the accept button is more realistic and ensures the site's JavaScript runs as it would for a real user. Blocking is faster but may miss issues.

Can I reuse the same cookie consent across multiple test files?

Yes, save the storage state after accepting cookies using context.storageState({ path: 'state.json' }), then load it in other tests with browser.newContext({ storageState: 'state.json' }).

What if the popup is not a GDPR cookie banner but a different kind of modal?

The same techniques apply: locate the close or accept button and click it. The key is to use a robust selector and wait for the element to be actionable.