keepcalculator

06 Numbers and Powers

Playwright Screenshots with Consent Popups

Card No. 06·54810 · Updated · Standard formula, shown below

This guide walks you through capturing clean product screenshots on pages that display consent or cookie popups using Playwright. You’ll learn how to detect, dismiss, or bypass these overlays so your screenshots show the actual product, not a cookie banner. We’ll cover the essential Playwright APIs, practical code examples, and common pitfalls to avoid.

What You’ll Need

  • A Node.js project with Playwright installed (npm install @playwright/test)
  • Basic familiarity with JavaScript/TypeScript and async/await
  • A target URL that has a consent popup (you can test with any site that shows one)

Step-by-Step

  1. Set up your test file. Create a file like screenshot.spec.js and import Playwright’s test and expect modules. Use the test function to define your test case.
  2. Launch a browser and create a page. Inside the test, use chromium.launch() to start a browser (or use Playwright’s default fixture). Then create a new page with browser.newPage(). For consistent screenshots, set a fixed viewport size, e.g., page.setViewportSize({ width: 1280, height: 720 }).
  3. Navigate to the target page. Use page.goto('https://example.com/product') with waitUntil: 'networkidle' to ensure all resources are loaded. This is crucial because popups often appear after initial load.
  4. Wait for the popup to appear. Consent popups are usually rendered after a short delay. Use page.waitForSelector('[data-testid="consent-banner"]', { timeout: 5000 }) to wait for the popup. If you’re not sure of the selector, you can use a more generic approach: wait for any element that matches common patterns like button:has-text("Accept") or #onetrust-banner-sdk (a common ID for OneTrust).
  5. Dismiss the popup. Once the popup is visible, click the accept or close button. Use page.click('button:has-text("Accept All")') or page.click('[aria-label="Close"]'). If the popup has a “Reject” or “Manage” option, you can click that instead. After clicking, wait for the popup to disappear: await page.waitForSelector('[data-testid="consent-banner"]', { state: 'detached' }).
  6. Handle popups that don’t disappear. Some popups are persistent or have animations. In that case, you can force-remove the element via JavaScript: await page.evaluate(() => { const el = document.querySelector('[data-testid="consent-banner"]'); if (el) el.remove(); }). This is a fallback if clicking doesn’t work.
  7. Take the screenshot. Use page.screenshot({ path: 'product.png', fullPage: true }) for a full-page screenshot, or page.screenshot({ path: 'product.png' }) for just the viewport. If you want to capture a specific element (like the product image), use page.locator('.product-image').screenshot({ path: 'product-image.png' }).
  8. Clean up. Close the browser at the end of the test to free resources: await browser.close().

Common Mistakes

  • Not waiting for the popup to appear. If you take a screenshot immediately after navigation, the popup might not have loaded yet, and your screenshot will miss it. Always wait for the popup selector.
  • Using a hard-coded delay. page.waitForTimeout(3000) is unreliable because popups load at different speeds. Use conditional waits on selectors instead.
  • Clicking the wrong button. Some popups have multiple buttons (Accept, Reject, Customize). Clicking the wrong one might not dismiss the popup or might trigger unexpected navigation. Inspect the DOM to find the correct selector.
  • Ignoring iframes. Many consent popups are embedded in iframes. If your selector doesn’t work, check if the popup is inside an iframe and use page.frame() to interact with it.
  • Not handling multiple popups. Some sites show a consent popup and then a newsletter signup or a promotional popup. You may need to dismiss several overlays before taking the screenshot.

Tips

  • Use a dedicated test environment. If possible, use a staging or test site where you can control the popup behavior (e.g., disable it via a query parameter or cookie).
  • Set cookies before navigation. If the site stores consent in a cookie, you can set that cookie before navigating, so the popup never appears. Use context.addCookies([{ name: 'consent', value: 'true', url: 'https://example.com' }]).
  • Use Playwright’s built-in acceptDownloads or ignoreHTTPSErrors if needed. These can help with other issues that might interfere with screenshot capture.
  • Take screenshots in a headless browser. Headless mode is faster and more reliable for automation. Use chromium.launch({ headless: true }).
  • Consider using page.locator().screenshot() for element-specific captures. This avoids issues with fixed headers or sticky popups that might cover the product.

Troubleshooting

Popup doesn’t appear in the selector wait. If waitForSelector times out, the popup might have a different selector than expected. Use page.locator('text=Accept') or page.locator('button:has-text("Agree")') as a fallback. You can also inspect the page’s HTML by running page.content() and searching for keywords like “cookie” or “consent”.

Clicking the button does nothing. The button might be disabled or hidden behind another element. Try page.click(selector, { force: true }) to bypass actionability checks. If that fails, use page.evaluate() to directly call the button’s click method: document.querySelector('button').click().

Popup reappears after dismissal. Some sites re-show the popup on scroll or after a few seconds. In that case, you can remove the element via JavaScript and also set a cookie to prevent it from appearing again. Alternatively, use page.addStyleTag({ content: '#consent-banner { display: none !important; }' }) to hide it permanently.

Iframe popup not interacting. If the popup is inside an iframe, you need to get the frame first: const frame = page.frames().find(f => f.url().includes('consent')). Then use frame.click('button') to interact with it.

Screenshot still shows the popup. If the popup is still visible after dismissal, it might be a separate element (e.g., a modal overlay). Check for other selectors like .modal or .overlay and remove them similarly.

Frequently Asked Questions

Can I bypass consent popups without interacting with them?

Yes, you can set a cookie before navigation that indicates consent, or use page.addInitScript() to override window.alert or window.confirm if the popup uses those. However, the most reliable method is to dismiss the popup as shown above.

How do I handle popups that appear after a delay?

Use page.waitForSelector(selector, { timeout: 10000 }) to wait for the popup to appear. If it appears after a scroll, you might need to scroll down first: page.mouse.wheel(0, 500).

What if the consent popup is different on mobile and desktop?

You can run separate tests with different viewport sizes. Use test.use({ viewport: { width: 375, height: 812 } }) for mobile. The popup selectors might differ, so adjust accordingly.

Is there a way to take a screenshot without the popup ever appearing?

Yes, by setting a consent cookie before navigation. Check the site’s network requests to find the cookie name and value, then use context.addCookies().

Can I take screenshots of multiple pages with popups in one test?

Absolutely. Loop through an array of URLs, navigate, dismiss the popup, and take a screenshot for each. Just make sure to reset any state between navigations.

What if the popup is a native browser dialog (like a geolocation prompt)?

That’s different from a consent popup. For native dialogs, use page.on('dialog', dialog => dialog.dismiss()) to auto-dismiss them.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →