Zimt

How to Remove Cookie Banners from PhantomJS Screenshots

· 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

Removing cookie banners from PhantomJS screenshots ensures clean, uninterrupted visual captures of web pages for testing, reporting, or monitoring. Cookie consent pop-ups are often injected by JavaScript after page load and can obstruct critical content in automated screenshots. By manipulating PhantomJS settings and injecting custom scripts, you can suppress or remove these banners before they appear or eliminate them immediately after rendering. This guide walks through the technical steps using PhantomJS’s API to achieve banner-free screenshots reliably and consistently.

What You'll Need

  • PhantomJS installed and accessible from the command line
  • Basic knowledge of JavaScript and the PhantomJS scripting environment
  • A target website URL that displays a cookie banner
  • Optional: a code editor to write and modify PhantomJS scripts

Step-by-Step

  1. Launch PhantomJS with a script file
    Create a new JavaScript file (e.g., screenshot.js) and initialize a PhantomJS script using require('webpage').create(). This creates a headless browser instance for navigation and rendering.
  2. Set viewport and page settings
    Configure the viewport size to match typical screen dimensions using page.viewportSize = { width: 1280, height: 800 }. This ensures consistent rendering. Optionally, enable JavaScript and images with page.settings.javascriptEnabled = true and page.settings.loadImages = true.
  3. Navigate to the target URL
    Use page.open() to load the web page. Pass the URL as the first argument and include a callback function to execute once the page finishes loading.
  4. Wait for full page load and banner appearance
    Since cookie banners often load asynchronously, use window.setTimeout() within the page context to delay further actions. A delay of 3–5 seconds is usually sufficient. Example: page.evaluate(function() { setTimeout(function() { /* next step */ }, 3000); });
  5. Identify the cookie banner element
    Inspect the target website to determine the CSS selector of the cookie banner container. Common selectors include #cookie-banner, .cookie-consent, or [id*="cookie"]. Use browser developer tools to confirm the exact selector.
  6. Remove the banner via DOM manipulation
    Use page.evaluate() to execute JavaScript in the page context that locates and removes the banner. Example:
    page.evaluate(function() {
      var banner = document.querySelector('.cookie-banner, #cookies, [class*="cookie"]');
      if (banner) {
        banner.style.display = 'none'; // or banner.remove();
      }
    });
    Using display: 'none' hides the element; remove() deletes it from the DOM.
  7. Handle multiple or dynamic banners
    If the site uses multiple consent layers or dynamically loads banners, extend the selector to catch variants. Use a broader selector like [id*="cookie"], [class*="consent"] or loop through common identifiers. Add logic to remove all matches:
    page.evaluate(function() {
      var banners = document.querySelectorAll('.cookie-banner, .cookie-modal, .gdpr-banner');
      banners.forEach(function(el) { el.remove(); });
    });
  8. Wait for removal to take effect
    After removing the banner, add a short delay (e.g., 500ms) to ensure the page re-renders without the element. This prevents race conditions when capturing the screenshot.
  9. Capture the screenshot
    Use page.render('screenshot.png') to save the image. Ensure this call happens after all removal logic and delays. The output will be a PNG file with the banner absent.
  10. Close the page and exit
    Add phantom.exit() at the end of the script to terminate PhantomJS cleanly and avoid hanging processes.

Common Mistakes

  • Not waiting long enough: Cookie banners may load after initial page render. Skipping a delay means the script runs before the banner exists, so removal fails.
  • Using incorrect CSS selectors: A typo or overly specific selector won't match the banner. Always verify selectors using browser dev tools.
  • Forgetting page.evaluate(): DOM manipulation must occur inside evaluate() because PhantomJS runs in a separate context from the page.
  • Assuming all banners use the same class: Different sites use varied class names. Hardcoding one selector limits reusability.
  • Not handling remove() browser support: Older browsers (and PhantomJS) may not support Element.remove(). Use element.parentNode.removeChild(element) for compatibility.

Tips

  • Use broad selectors with wildcards: Combine common patterns like [class*="cookie"] or [id*="gdpr"] to catch variations.
  • Log banner elements for debugging: Inside page.evaluate(), use console.log() to print found elements. Enable page.onConsoleMessage to see output.
  • Test selectors in-browser first: Paste them into document.querySelector() in the browser console to confirm they work.
  • Set a longer timeout if needed: For slow-loading sites, increase the setTimeout delay or use network idle detection via page.onResourceTimeout.
  • Use display: 'none' instead of remove() if layout shifts: Some pages reflow awkwardly when elements are deleted. Hiding preserves layout.

Troubleshooting

If the cookie banner still appears in the screenshot:

  • Check selector accuracy: Confirm the banner element matches your selector. Use page.evaluate() to return document.querySelectorAll('.your-selector') and log the count.
  • Verify timing: Add a console.log('Banner removed') inside evaluate() and ensure it appears after the banner should be present.
  • Inspect PhantomJS version: Older versions may not support modern JavaScript. Use PhantomJS 2.1.1 or later for better compatibility.
  • Check for iframe-embedded banners: Some banners load in iframes. You’ll need to switch context or block the iframe source via page.onResourceRequested.
  • Handle script-generated banners: If the banner is added by a third-party script, consider blocking that script using page.onResourceRequested to filter requests by URL.

Frequently Asked Questions

Can I block cookie banners by disabling JavaScript?

Disabling JavaScript may prevent banners from loading, but it also breaks core site functionality. It’s better to allow JS and remove the banner selectively.

Does this method work on all websites?

No. Sites with complex, dynamically generated banners or anti-bot measures may require additional logic or fail entirely. This method works best on standard implementations.

Is PhantomJS still supported?

PhantomJS is no longer actively maintained. For long-term projects, consider migrating to Puppeteer with headless Chrome.

Can I remove banners without knowing the exact selector?

You can write generic scripts that check multiple common selectors, but some manual tuning per site is usually needed for reliability.

Will this affect the page's functionality?

Removing the banner DOM element doesn’t affect consent logic unless the site checks for user interaction. For testing, this is usually acceptable.

Can I automate this for multiple URLs?

Yes. Wrap the logic in a function and loop through an array of URLs, adjusting selectors per site as needed.