Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a normal cookie banner rendered in the page, either click its consent button and wait for it to disappear, reuse a saved Playwright storage state, or hide it with screenshot-only CSS. Click and save consent when you need the site’s real consent flow; use CSS when you only need a clean capture. These approaches are different: hiding a banner changes the screenshot, not the site’s consent state.

Choose the right way to remove the banner

Method Use it when What it changes
Click a consent control You want the site to record a real visitor choice. Runs the site’s consent flow; the banner should then disappear.
Reuse storage state You repeat captures and consent is stored in cookies or origin localStorage. Starts a new context with saved browser state.
Screenshot-time CSS You need a clean image but do not need to interact with the consent flow. Changes the screenshot rendering only; it does not accept consent.
Mask a locator You are comparing screenshots and want to exclude the banner’s pixels. Covers the element in the comparison image; it does not remove the UI.

Use selectors specific to the site. A generic selector can conceal a legitimate dialog or page content, while consent controls, storage keys, and iframe arrangements vary by site.

Click consent and wait before capturing

A typical banner is ordinary page DOM, so use Playwright locators rather than the browser-dialog event. Locate the banner, find its accept control inside it, click, and wait until it is hidden before taking the screenshot.

import { chromium } from 'playwright';

const browser = await chromium.launch();
const page = await browser.newPage();

try {
  await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });

  const banner = page.getByRole('dialog', { name: /cookie|consent/i });
  const accept = banner.getByRole('button', { name: /accept|agree|allow all/i });

  if (await banner.isVisible().catch(() => false)) {
    await accept.click();
    await banner.waitFor({ state: 'hidden' });
  }

  await page.screenshot({ path: 'page.png', fullPage: true });
} finally {
  await browser.close();
}

The role and accessible name are examples, not universal selectors. Prefer a site-provided test ID, accessible role and label, or another stable site-specific locator. Keep the accept button scoped to the banner so a different “Accept” button elsewhere on the page cannot be clicked accidentally.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The visibility check handles the case where no matching banner is visible. It does not make a wrong locator correct: if a visible banner appears but the accept locator finds no button, the click should fail rather than silently produce a misleading capture. If the site offers “Reject” or “Manage preferences” and that is the choice you intend to represent, target that control instead.

When the banner is in an iframe

Find the frame that contains the banner, then use the same locator-and-wait sequence on that frame. A locator on the top-level page cannot reach elements inside a separate frame. For cross-origin consent, storage may also be scoped to a different domain; check the frame’s origin and the site’s actual consent behavior rather than assuming a top-level cookie is sufficient.

Save consent for later screenshot runs

After completing the consent flow once, save the browser context’s storage state. A later context can load it before navigating, so the site may recognize the saved consent without requiring another click.

import { chromium } from 'playwright';

const browser = await chromium.launch();
const setupContext = await browser.newContext();
const setupPage = await setupContext.newPage();

try {
  await setupPage.goto('https://example.com');
  await setupPage.getByRole('button', { name: /accept/i }).click();
  await setupPage.context().storageState({ path: 'playwright/.auth/consent.json' });

  const context = await browser.newContext({
    storageState: 'playwright/.auth/consent.json',
  });
  const page = await context.newPage();
  await page.goto('https://example.com');
  await page.screenshot({ path: 'page.png', fullPage: true });
  await context.close();
} finally {
  await setupContext.close();
  await browser.close();
}

Playwright storage state includes cookies and origin localStorage; the documentation also says it is interchangeable between BrowserContext and APIRequestContext. See the Playwright authentication documentation and API testing guide.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Saved state is not guaranteed to work indefinitely. The site may expire consent, change its storage scheme, require additional session data, or store consent on another origin. Keep state files out of public repositories if they contain sensitive cookies, and refresh the state by repeating the real consent flow if the banner returns.

Hide the banner only in the screenshot

Playwright’s screenshot style option injects CSS for the capture. This is useful when you want a clean image but do not want to click or alter the page’s consent state.

#1 Best Overall
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
import { chromium } from 'playwright';

const browser = await chromium.launch();
const page = await browser.newPage();

try {
  await page.goto('https://example.com');
  await page.screenshot({
    path: 'page.png',
    fullPage: true,
    style: `
      [role="dialog"][aria-label*="cookie" i],
      .cookie-banner,
      .cookie-consent,
      .consent-backdrop {
        display: none !important;
      }
    `,
  });
} finally {
  await browser.close();
}

The selectors above are illustrative; inspect the target page and replace them with narrowly scoped selectors that match its banner and backdrop. Playwright documents style for repeatable screenshots, including hiding dynamic elements; it can pierce Shadow DOM and apply styles to inner frames. See the Page screenshot API.

Because the stylesheet applies to the capture rather than permanently changing the page, subsequent page actions are not a substitute for a recorded consent choice. If you need to show the experience of an approved session, use the site’s actual consent flow and, where appropriate, saved state.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use stylePath or mask for visual tests

For Playwright visual assertions, put capture-only CSS in a fixture file and pass its path as stylePath. Use mask when the element may remain on the page but its pixels should be covered in the comparison.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
import { expect } from '@playwright/test';

await expect(page).toHaveScreenshot('homepage.png', {
  stylePath: 'tests/fixtures/hide-consent.css',
});

A stylesheet can hide the banner for a baseline intended to omit it. A mask overlays matched locators; it does not remove the banner or reproduce a naturally consented page. For the assertion options, see Playwright PageAssertions documentation.

Why page.on(‘dialog’) usually does not help

page.on('dialog') handles JavaScript alert, confirm, prompt, and beforeunload dialogs—not a cookie-consent component rendered as a page element. Playwright says JavaScript dialogs are auto-dismissed when there is no dialog listener; once you install a listener, the handler must accept or dismiss the dialog or the triggering action can stall. See Playwright dialogs documentation.

page.on('dialog', async dialog => {
  await dialog.dismiss();
});

Use that handler only if the site actually triggers a browser dialog. It will not click a DOM banner’s accept button or remove an HTML overlay.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshoot banners that remain in the capture

  • The banner is not found: Check whether it is inside an iframe or Shadow DOM, whether it appears after navigation, and whether the role/name matches the rendered element. Prefer a site-specific locator over broad text matching.
  • The click times out: Confirm the consent button is visible and enabled, and scope it to the banner. A backdrop, animation, or a different consent panel may be intercepting interaction. Inspect the page state instead of adding an arbitrary delay as the only fix.
  • The screenshot is taken too early: Wait for the banner to become hidden or detached after the click. If it is rendered asynchronously, wait for a reliable site-specific locator or condition before capture.
  • The banner returns in a new run: Save storage state after consent and load it into the later context. If it still returns, consent may have expired or live in a different origin, cookie scope, or storage mechanism.
  • CSS hides the banner but leaves a dim overlay: Identify and hide the site-specific backdrop as well as the banner. Do not broadly hide every fixed or modal element; that can remove unrelated UI.
  • A legitimate dialog disappears: Narrow the CSS selector to the consent component, including a site-specific class or attribute, rather than hiding all elements with role="dialog".
  • Masking still looks wrong: A mask covers matched pixels; it does not collapse the element or remove its layout effects. Use screenshot CSS or actual consent setup if the banner must not occupy space.

Or skip the browser setup

If you need an image or PDF without maintaining browser automation, ScreenshotNeo is a website screenshot API and MCP server for developers. Its GET endpoint accepts a URL and returns a screenshot or PDF. For a WebP screenshot of the example page:

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.
curl -G "https://api.screenshotneo.com/v1/shot" 
  -d access_key=YOUR_API_KEY 
  --data-urlencode url=https://example.com 
  -o shot.webp

See the ScreenshotNeo API documentation for request options and response details. ScreenshotNeo accepts cookie/consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks/CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, with response headers identifying the page verdict and billing status. Its MCP server includes take_screenshot, get_page_info, and capture_pdf for AI agents. The free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots.

Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.

Choose based on what the screenshot needs to mean

When the image should reflect a visitor who made a consent choice, click the appropriate control and reuse storage state where it remains valid. When consent is outside the purpose of the image, screenshot-only CSS is the direct option. For repeatable visual tests, use a scoped style fixture or mask according to whether the banner should disappear or merely be excluded from pixel comparison.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Frequently Asked Questions

Can I hide a cookie banner without accepting cookies?

Yes. Use the screenshot `style` option or `stylePath` to hide it for capture. That changes the rendered screenshot, not the site’s consent record.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

Does Playwright storageState save localStorage?

It includes cookies and origin localStorage. A site may use other or additional state, so confirm that the saved context suppresses the banner on the target site.

Will page.on(‘dialog’) remove a cookie banner?

No. It handles JavaScript browser dialogs, not consent UI rendered in the page DOM.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.