Zimt

Puppeteer: How to Click Cookie Popups and Modal Alerts

· 5 min read · Cookies and Bars

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To click cookie popups and modal alerts in Puppeteer, you must identify the unique CSS selector of the "Accept" or "Close" button and use the page.click() method after ensuring the element is visible and clickable. Because these modals often load asynchronously or appear after a short delay, combining page.waitForSelector() with a conditional check prevents the script from crashing when a popup does not appear on every page load.

What You'll Need

  • Node.js installed on your system.
  • The puppeteer package installed via npm (npm install puppeteer).
  • Chrome or Chromium browser (bundled with Puppeteer).
  • Basic knowledge of CSS selectors to target specific buttons.

Step-by-Step

  1. Launch the Browser and Navigate: Start by launching your Puppeteer instance and navigating to the target URL. Use headless: false during development so you can visually confirm if the popup is appearing as expected.
  2. Inspect the Popup Element: Open the website in a standard browser, right-click the "Accept Cookies" or "Close" button, and select "Inspect". Look for a unique ID, a specific class name, or a combination of attributes (e.g., button[id="cookie-accept"] or .modal-close-btn) that uniquely identifies the button.
  3. Wait for the Selector: Popups rarely appear the instant the page loads. Use page.waitForSelector('.your-button-class'). To prevent your script from hanging indefinitely if the popup doesn't appear (which happens often with A/B testing or regional settings), wrap this in a try...catch block or set a short timeout.
  4. Handle the Click Action: Once the selector is found, execute await page.click('.your-button-class'). If the button is covered by another transparent element, you may need to use page.evaluate() to trigger a click via the DOM directly: await page.evaluate(() => document.querySelector('.your-button-class').click());.
  5. Verify the Modal is Gone: To ensure the page is now interactable, wait for the modal container to disappear from the DOM or become hidden. Use page.waitForSelector('.modal-overlay', { hidden: true }). This ensures that subsequent clicks on the main page content are not blocked by a fading animation.
  6. Manage Browser Alerts: If the "popup" is actually a native browser alert(), confirm(), or prompt(), page.click() will not work. You must set up a dialog handler before navigating: page.on('dialog', async dialog => { await dialog.accept(); });.

Common Mistakes

  • Ignoring Asynchronous Loading: Attempting to click a button immediately after page.goto(). Most cookie banners use JavaScript to trigger after the initial DOM load, leading to "element not found" errors.
  • Using Non-Unique Selectors: Using a generic class like .btn that might exist multiple times on the page. Always use the most specific selector possible.
  • Forgetting the Overlay: Clicking the button but failing to wait for the semi-transparent background overlay to vanish. This often results in an "Element is not clickable at point" error for the next action.
  • Confusing Modals with Dialogs: Trying to use CSS selectors on native browser alerts. Native alerts are part of the browser UI, not the HTML DOM, and require the page.on('dialog') listener.

Tips

  • Use Text-Based Selectors: If classes are randomized (common in modern frameworks), use page.evaluate() to find a button containing specific text like "Accept All" or "I Agree".
  • Set a Reasonable Timeout: Instead of the default 30-second timeout, set page.waitForSelector('.btn', { timeout: 5000 }). This allows your script to move on quickly if the popup doesn't appear.
  • Use Stealth Plugin: Some sites detect Puppeteer and refuse to show popups or block the browser entirely. Using puppeteer-extra-plugin-stealth can help you appear as a real user.
  • Cookie Injection: If you have to deal with the same popup on every page, consider finding the cookie the site sets after you click "Accept" and inject that cookie into the browser session using page.setCookie() to bypass the popup entirely.

Troubleshooting

If your script fails to click the popup, first check if the element is inside an iframe. Puppeteer cannot click an element inside an iframe using page.click(). You must first find the frame using page.frames() or page.waitForFrame(), then call the click method on that specific frame object.

If the button is visible but the click does nothing, the site may be detecting the "trusted" property of the click event. In this case, use page.evaluate() to trigger the click via the browser's internal JavaScript engine, which bypasses some of the synthetic event restrictions.

If the popup appears randomly, wrap your clicking logic in a function and call it at the start of every new page navigation, utilizing a try...catch block to ensure the script continues even if the selector is not found.

Frequently Asked Questions

How do I handle a popup that only appears sometimes?

Wrap your waitForSelector and click logic in a try...catch block with a short timeout (e.g., 3-5 seconds). If the element isn't found, the catch block will trigger, allowing the script to continue without crashing.

Can I bypass cookie popups without clicking them?

Yes, by identifying the cookie the site saves after a user accepts the terms. You can use page.setCookie() to add that specific cookie to the browser instance before navigating to the page.

What is the difference between a modal and a dialog in Puppeteer?

A modal is an HTML element (div, button) rendered within the page's DOM. A dialog is a native browser window (like window.alert). Modals are handled via CSS selectors; dialogs are handled via the page.on('dialog') event.

Why does Puppeteer say the element is not clickable?

This usually happens because the element is obscured by another element (like a loading spinner or a transparent overlay) or it hasn't finished its entry animation. Use page.waitForSelector(selector, { visible: true }) to ensure it is fully rendered.

How do I click a button based on its text?

Puppeteer doesn't have a native clickByText method. You can achieve this using page.evaluate() to loop through all buttons and click the one whose innerText matches your target string.