Fix Playwright Cookie Banners That Won’t Close
Playwright tests often stall when a cookie consent banner refuses to disappear, causing false negatives and wasted CI minutes. This guide shows how to reliably detect, interact with, and dismiss stubborn banners so your scripts continue uninterrupted.
What You'll Need
- Node.js (v14 or newer) installed on your machine
- Playwright package (npm i -D @playwright/test)
- Access to the source code of the test suite you are maintaining
- Basic knowledge of CSS selectors and async/await syntax
Step-by-Step
- Identify the banner element. Open the page in a regular browser, right‑click the banner, and choose Inspect. Look for a unique container ID, class, or data attribute. If the banner is generated by a third‑party script (e.g., OneTrust, Cookiebot), note the wrapper element that changes when the user accepts.
-
Write a selector that is both specific and resilient. Prefer attributes that are unlikely to change on a redesign, such as
data-cookie-consentor a stable#cookie-banner. Avoid generic tags likedivalone. Example:const banner = page.locator('[data-cookie-consent]'); -
Wait for the banner to become visible. Use Playwright’s built‑in waiting mechanisms to avoid race conditions:
If the banner appears after a delay (e.g., after a script loads), increase the timeout or useawait expect(banner).toBeVisible({ timeout: 5000 });page.waitForLoadState('networkidle')before checking. -
Click the accept or close button. Locate the button inside the banner. A common pattern is a button with text like “Accept”, “Agree”, or an
aria-labelof “Close”. Example:
If the button is hidden behind a shadow DOM, useconst acceptBtn = banner.locator('button:has-text("Accept")'); await acceptBtn.click();page.evaluateto pierce the shadow root. -
Verify that the banner disappears. After clicking, assert that the container is hidden or detached:
If the banner remains, proceed to a fallback strategy.await expect(banner).toBeHidden({ timeout: 3000 }); -
Implement a fallback JavaScript snippet. Some banners ignore synthetic click events. Inject a small script that directly sets the consent cookie or removes the element:
This approach works when the site respects the cookie but does not require a UI interaction.await page.evaluate(() => { document.querySelector('[data-cookie-consent]')?.remove(); document.cookie = 'cookie_consent=accepted; path=/; max-age=31536000'; }); -
Encapsulate the logic in a reusable helper. Create a function like
async function dismissCookieBanner(page) { … }and call it at the start of every test or in a globalbeforeEachhook. This keeps the code DRY and ensures consistency across suites. -
Handle variations across locales. If your site serves multiple languages, the button text will differ. Use a regex selector that matches any common term:
Or rely on a data attribute that stays constant across translations.const acceptBtn = banner.locator('button:has-text(/accept|agree|ok|verstanden/i)'); -
Account for iframes. Some consent managers embed the banner in an iframe. First locate the iframe, then operate inside it:
Remember to wait for the iframe to load before interacting.const frame = page.frame({ url: /consent/ }); const btn = frame.locator('button:has-text("Accept")'); await btn.click(); -
Run the test in headless and headed modes. Occasionally a banner behaves differently when the browser is headless. Execute the same script with
headless: falselocally to confirm that the selector works in both environments.
Common Mistakes
- Using overly generic selectors like
divorbuttonthat match multiple elements and cause the click to hit the wrong target. - Assuming the banner is present on every page; some routes load without a consent prompt, leading to timeout errors.
- Relying on
page.click()with a raw selector instead of the PlaywrightLocatorAPI, which loses built‑in auto‑waiting. - Neglecting to clear cookies between tests, so a previous acceptance masks the banner and hides a regression.
- Injecting a fallback script before the page finishes loading, which may re‑add the banner later.
Tips
- Prefer
await expect(locator).toBeVisible()over manualwaitForTimeout; it adapts to network speed. - Store the consent cookie name in a constant; if the provider changes it, you only edit one place.
- When working with third‑party consent managers, consult their documentation for a JavaScript API that can programmatically set consent.
- Use Playwright’s
test.afterEachhook to delete the consent cookie, guaranteeing a fresh state for the next test. - Run a quick sanity check with
npx playwright show-reportto verify that the banner really disappeared before the next interaction.
Troubleshooting
If the banner still blocks the flow after following the steps above, try the following diagnostics:
- Check console errors. Open the DevTools console in a headed run and look for CSP violations or JavaScript errors that prevent the click handler from firing.
- Confirm the selector after page navigation. Some sites replace the banner DOM on navigation; re‑evaluate the locator after each
page.goto. - Validate cookie persistence. After the fallback script runs, read
document.cookiein the page context to ensure the consent flag is set. - Use
page.waitForFunctionas a last resort. Example:
This polls until the element is gone, but it is slower than a direct assertion.await page.waitForFunction(() => !document.querySelector('[data-cookie-consent]')); - Inspect the iframe hierarchy. Some consent managers load the banner inside a nested iframe that only appears after a third‑party script finishes. Use
page.waitForSelector('iframe[src*="consent"]')before switching context.
Frequently Asked Questions
Can I disable cookie banners entirely for test environments?
Yes. Many consent managers provide a URL parameter or a special cookie (e.g., _consent=disable) that suppresses the UI. Adding this to your test launch URL is often the cleanest solution.
Why does await button.click() sometimes do nothing?
Playwright may dispatch a synthetic click that the banner’s script ignores if it checks for a genuine user gesture. Using button.evaluate(node => node.click()) or setting the consent cookie directly bypasses that check.
Is it safe to remove the banner element with remove()?
Removing the element is safe for test stability, but it does not set the underlying consent cookie. If the application reads the cookie to decide feature availability, also set the cookie as shown in the fallback snippet.
What if the banner appears only after a scroll event?
Scroll the page to trigger the banner, then run the same detection logic. Playwright’s page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)) can be used before attempting dismissal.
Do I need to handle GDPR‑specific banners differently?
The technical handling is the same; the difference lies in the consent values stored. Ensure you set the correct cookie name and value that the site expects for a GDPR‑compliant acceptance.
How can I make the solution work across multiple domains?
Encapsulate the dismissal logic in a helper that accepts a Page object and a map of domain‑specific selectors. The helper can detect the current URL and apply the appropriate selector set.