October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
browser automation

How to Click Cookie Popups and Modal Alerts in Puppeteer

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

First identify which kind of “popup” you have. A cookie banner or in-page modal is part of the document: locate its intended control and click it with a Puppeteer locator. A native JavaScript alert, confirm, prompt, or beforeunload dialog is handled through the page’s dialog event, then accepted or dismissed deliberately. If the action navigates, start waitForNavigation() at the same time as the click so you do not miss the navigation.

Tell an HTML popup from a native JavaScript dialog

People use “popup” to mean two different browser behaviors, and Puppeteer handles them differently. A cookie banner or designed modal is rendered in the page. It has DOM elements such as buttons, links, or inputs; use a locator or selector to interact with those elements. A JavaScript dialog is browser-native and is surfaced as a Puppeteer dialog event; it does not have a page button that you can find with a CSS selector.

Page-rendered banner or modal Native JavaScript dialog
Part of the page DOM; inspect it and locate the specific control. Reported through the page’s dialog event.
Click with a locator or selector; locators wait for an actionable element. Respond with dialog.accept() or dialog.dismiss().
Verify the resulting page state, because site markup and consent behavior vary. Register a handler before the action that opens it and choose the response intentionally.

Puppeteer’s interaction guide says, “Locators is the recommended way to select an element and interact with them.” See the Puppeteer page interactions guide and the PageEvent reference. The examples below follow the current documentation pattern; the page-interactions guide and Page.click reference were listed for Puppeteer 25.12.0. Check the documentation for the version installed in your project if an API or behavior differs.

Click a cookie banner or HTML modal

Inspect the actual consent action

Decide what the automation should do before clicking. “Accept all,” “Reject non-essential,” and “Manage preferences” are different choices, and a test should exercise the one it is meant to exercise. Inspect the rendered page, including accessible names and attributes, and choose a locator that identifies that action rather than a generic word that could match several controls.

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

For example, if the site really exposes a button with the accessible label shown here, click it like this:

await page.locator('button[aria-label="Accept cookies"]').click();

This selector is illustrative, not universal. Real sites use different labels and markup; the control might be inside a frame or shadow root. Puppeteer’s locator selectors can use CSS, text, accessibility attributes, XPath, and Shadow DOM syntax. See Page interactions for selector and locator guidance. Prefer a selector that states both what the control is and where it belongs, where possible, so an unrelated “Accept” or “Continue” button is not clicked.

Use locators rather than sleeps as the default

A locator waits for an element to be in a suitable state before acting, including being present in the viewport, visible, enabled, and having a stable bounding box. That makes it a better starting point than adding an arbitrary delay and hoping the banner has appeared. After the click, assert the outcome your test cares about—for example, that the banner is gone or that the expected page content is visible. A successful click alone does not prove the site recorded the intended consent choice.

If a locator cannot express the interaction you need, Puppeteer also documents lower-level methods such as waitForSelector() and element handles. Waiting for a selector only establishes that the selected element exists or meets the requested visibility condition; it does not automatically retry a later click if that action fails. Consult the interaction guide for the current options.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

Account for multiple matches

A selector can match more than one element—for example, a banner and a settings dialog might both contain an “Accept” control. Page.click(selector) clicks the first match, scrolls it into view, and clicks its center. It rejects if nothing matches, but a first-match click is not a substitute for selecting the intended control. Make the selector specific and verify the page after acting. These behaviors are documented in Page.click.

Handle native JavaScript alerts, confirms, prompts, and unload dialogs

Attach a listener before the action that could open the dialog. Decide whether the correct outcome is to accept or dismiss; do not automatically accept every dialog, because acceptance can submit data, confirm a destructive action, or change a test’s result. For a prompt, pass the intended text to accept() if the flow requires input.

page.once('dialog', async dialog => {
  console.log(`Dialog type: ${dialog.type()}; message: ${dialog.message()}`);
  await dialog.accept(); // Use dialog.dismiss() if the intended behavior is to cancel.
});

await page.locator('button.show-alert').click();

The example accepts the next dialog because that is the chosen flow; replace it with dismissal or prompt input where appropriate. Registering the one-time handler before the click matters: if the dialog opens first, the code may wait indefinitely or leave the dialog unhandled. The event and response methods are described in Puppeteer’s PageEvent and Dialog references.

Wait safely when the click navigates

If a click causes a document navigation, start the navigation wait and click together with Promise.all. Starting the wait after the click risks missing a fast navigation event.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const [response] = await Promise.all([
  page.waitForNavigation(),
  page.locator('button.continue').click(),
]);

The sample assumes the control really navigates the page. Use the actual locator and navigation wait options appropriate to the site and your test. The documented concurrent pattern is in Page.waitForNavigation.

When the popup may or may not appear

Intermittent banners need a deliberate branch, not a blind click or a long fixed sleep. Treat the banner as optional only if the test’s purpose allows either outcome. If consent is essential to the scenario, a missing banner should be reported as a test failure rather than silently skipped.

  1. Navigate to the page and use a locator for the specific consent action.
  2. Set a bounded wait appropriate to the test for that locator or for the banner’s container.
  3. If it appears, click the intended action and verify the resulting state.
  4. If it does not appear, continue only when the scenario explicitly permits a no-banner state; otherwise fail with a useful diagnostic.

A locator click waits for an actionable target, but the automation still needs a policy for an optional banner and a bounded timeout. Avoid catching every error and treating it as “no banner”: a timeout, an ambiguous selector, or a genuine interaction failure can otherwise be hidden as a successful test. The community question “How to handle pop up which may or may not appear?” is a useful description of this branch, but it does not establish how often banners appear or why a particular site omits one.

Cookie storage is not the same as making a consent choice

For repeatable tests, Puppeteer supports browser storage operations and saving or restoring cookies. That can be useful when the test is specifically about a previously established browser state. It is not a universal replacement for clicking a consent control: sites can use different storage and application logic, and setting a cookie does not establish that a valid consent choice was made. Verify the target site’s behavior and follow the requirements that apply to your use case.

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

The current Puppeteer Page API marks page-level cookie methods deprecated in favor of browser- or browser-context-level cookie APIs. See the Puppeteer cookies guide and the Page.cookies API reference before choosing an API for your installed version.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot failed or unreliable clicks

  • “No element found” or a locator timeout: Confirm the banner actually appeared, inspect the live markup, and check for a frame or shadow root. Do not assume every site uses the same consent platform or label.
  • The wrong button was clicked: The selector may match multiple controls. Narrow it to the relevant banner or use a more specific accessible name, then verify the resulting state. For Page.click(), remember that the first match is used.
  • The element exists but the interaction fails: Check whether it is visible, enabled, and stable, and whether another overlay is intercepting the action. Prefer a locator, whose actionability waits address common timing issues; use lower-level waits only when they fit the case.
  • The test hangs on an alert: Install a dialog listener before triggering the action and ensure the handler accepts or dismisses the dialog. A DOM selector cannot operate a native dialog.
  • The page navigates but the test misses it: Start waitForNavigation() concurrently with the click using Promise.all; do not attach the wait only after clicking.
  • The banner returns on the next run: The test may be using a fresh browser context, or the site may store consent in a different way. Inspect the actual storage and behavior rather than assuming a cookie alone persists the choice.
  • A cookie API example is deprecated: Follow the current Browser or BrowserContext cookie API documentation for your Puppeteer version instead of relying on Page-level methods.

Or skip the browser setup:

If you need a clean screenshot rather than a Puppeteer interaction test, ScreenshotNeo is a website screenshot API and MCP server. It does not make a consent choice for your test; it accepts cookie/consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture, with each step configurable. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing outcome. Its MCP server gives AI agents tools to take screenshots, get page info, and capture PDFs. The API also supports PNG, JPEG, or WebP screenshots and PDF output.

One GET request can return a screenshot; see the ScreenshotNeo API documentation for request options and response details:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots. For actual browser automation that must click a specific accept, reject, or settings control, keep using the Puppeteer approach above.

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

Create a free ScreenshotNeo account and get 1,000 screenshots a month with no card.

Frequently Asked Questions

Can Puppeteer click a browser-native alert with a CSS selector?

No. Native JavaScript dialogs are handled through the page’s dialog event, not as DOM elements.

Does dismissing a cookie banner prove that consent was saved?

No. Verify the site’s resulting state and storage behavior; removing or dismissing an interface alone does not establish how consent was recorded.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Read next

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.