How to Handle Cookie Consent Prompts with Puppeteer
In this article
Automating a website with Puppeteer often hits a cookie consent banner that blocks clicks or adds unwanted overhead. This guide shows you how to detect, accept, or dismiss those prompts reliably, and how to avoid common pitfalls like missing selectors or timing issues.
What You'll Need
- Node.js (v14 or later) installed
- A project with Puppeteer installed (
npm install puppeteer) - Basic familiarity with async/await in JavaScript
Step-by-Step
- Launch a browser instance. Create a script that launches Puppeteer with
puppeteer.launch(). For testing, setheadless: falseso you can watch what happens; for production, useheadless: 'new'(ortruein older versions). - Set a common user agent. Many sites show different cookie banners based on geography or device. Use
page.setUserAgent()to mimic a standard desktop Chrome user agent to get a typical consent flow. - Navigate to the target page. Use
page.goto(url, { waitUntil: 'networkidle2' }). This waits until the network is mostly idle, which often lets the banner appear. - Wait for the consent prompt. Use
page.waitForSelector()with a selector that matches the “Accept” button or the banner container. Common selectors includebutton:has-text("Accept"),#cookie-accept, or.cookie-banner. If you’re not sure, inspect the page manually or usepage.waitForTimeout(2000)as a fallback. - Decide on a strategy. You can either accept the cookies, reject them, or close the banner. For most automation, accepting is simplest. But if you need to test a “reject” path, look for a “Reject” or “Decline” button.
- Click the button. Use
page.click()with the selector. If the button is inside an iframe or shadow DOM, you’ll need to handle it separately (see Tips). - Wait for the banner to disappear. After clicking, wait for the selector to be hidden or removed:
page.waitForSelector(selector, { hidden: true }). This ensures the overlay is gone before you interact with the page content. - Proceed with your automation. Now you can click other elements, fill forms, or scrape data without the banner blocking your actions.
Common Mistakes
- Using a hard-coded selector without verifying it. Cookie banners vary widely; what works on one site may not exist on another. Always inspect the DOM first.
- Clicking too early. The banner may not be fully rendered when you try to click. Always wait for the selector to be visible and enabled.
- Ignoring iframes. Some consent prompts live in an iframe (e.g., OneTrust). You need to switch to that iframe before clicking.
- Not handling multiple banners. Some sites show a second layer (e.g., “Manage preferences”) after the initial accept. You may need to handle both.
- Assuming the banner is always present. If the site doesn’t show a banner (e.g., because of EU consent law exemptions), your script will fail. Always check for its existence first.
Tips
- Use a helper function. Write a reusable
acceptCookies(page)function that checks for the banner, clicks the right button, and returns a boolean indicating whether it acted. - Prefer text-based selectors. Use
page.evaluate()withArray.from(document.querySelectorAll('button')).find(b => b.textContent.includes('Accept'))to find buttons by text, which is more robust than class names that change. - Set a default timeout. Use
page.setDefaultTimeout(10000)so that waiting for the banner doesn’t hang forever. - Consider using the
--disable-blink-features=AutomationControlledflag. This can prevent some sites from detecting Puppeteer and showing a different consent flow. - Store cookies after accepting. If you’re doing multiple runs, save the
page.cookies()to a file and reload them on the next run to skip the banner entirely.
Troubleshooting
- Banner never appears. Try increasing the wait time, or use
page.waitForNavigation()after a click that triggers the banner. Also check if the banner is inside a shadow root (see below). - Selector not found. Open the page in a regular browser, right-click the banner, and inspect the element. Look for unique IDs or data attributes. If the banner is dynamically loaded, use
waitForSelectorwith a longer timeout. - Click does nothing. The button might be covered by another element. Use
page.evaluate()to callelement.click()directly, or usepage.mouse.click()after getting the element’s bounding box. - Iframe issues. If the banner is in an iframe, first wait for the iframe to load, then use
const frame = page.frames().find(f => f.url().includes('consent'))and thenframe.click(). - Shadow DOM. Some banners are inside a shadow root. Use
page.evaluateHandle()to pierce the shadow root and click the button manually. - Consent manager appears after navigation. If the banner appears only after a click or scroll, trigger that action first, then wait for the banner.
Frequently Asked Questions
Can I skip the banner entirely?
Yes, by saving cookies after accepting once and reloading them on subsequent runs. Use page.setCookie(...cookies) before navigating.
What if the site uses a consent management platform like OneTrust?
OneTrust often uses iframes. You’ll need to switch to the iframe and click the button inside. Look for an iframe with a URL containing 'onetrust' or 'consent'.
How do I handle a banner that appears after a delay?
Use page.waitForSelector(selector, { timeout: 15000 }) to wait up to 15 seconds. If it’s still not there, the banner may not be present.
Is it legal to bypass cookie consent for scraping?
That depends on your jurisdiction and the site’s terms. For personal testing, it’s usually fine, but for production scraping, you should respect the site’s consent choices and only automate what you’re allowed to.
Can I use Puppeteer with a proxy to avoid geo-specific banners?
Yes, you can pass a proxy via puppeteer.launch({ args: ['--proxy-server=...'] }). This may change the consent banner you get.
What if the banner has no “Accept” button, only “OK” or a close icon?
Look for any button that closes the banner, such as a close (X) button. Use its selector or text. If there’s no button at all, you might need to set a cookie to hide it, or use a browser extension.