Injecting CSS into a Site with Puppeteer: A Comprehensive Guide

Injecting CSS into a Site with Puppeteer: A Comprehensive Guide

21 May 2024 Stephan Petzl Leave a comment Tech-Help

When running automated tests on a website with Puppeteer, you may encounter scenarios where popups or other elements obstruct buttons or other interactive elements. This can impede the test script from functioning correctly. One effective solution is to inject custom CSS into the site to hide or modify these obstructive elements. This article provides a step-by-step guide on how to achieve this using Puppeteer.

Using page.addStyleTag Method

The page.addStyleTag method is a versatile way to inject CSS into a page. You can add a link or style tag based on different options such as a URL, a path, or direct CSS content.

Example Usage

  • URL:
await page.addStyleTag({url: 'http://example.com/style.css'});
  • Path: (can be relative or absolute)
  • await page.addStyleTag({path: 'style.css'});
  • Content:
  • await page.addStyleTag({content: '.body{background: red}'});

    Applying CSS on Every Page/Navigation

    If you need the CSS to be applied on each page or navigation, the page.evaluateOnNewDocument method is ideal. This method ensures that the CSS is injected into every new document loaded by the browser.

    Example Usage

    await page.evaluateOnNewDocument(() => {
      var style = document.createElement('style');
      style.type = 'text/css';
      style.innerHTML = '.body{background: red}'; // your CSS content here
      document.getElementsByTagName('head')[0].appendChild(style);
    });

    Alternative Method: page.evaluate

    Another method to inject CSS is using page.evaluate. This method allows you to inject both external stylesheets and raw CSS content directly into the current page.

    Injecting a Stylesheet

    await page.evaluate(async () => {
      const link = document.createElement('link');
      link.rel = 'stylesheet';
      link.href = 'https://example.com/style.css';
      const promise = new Promise((resolve, reject) => {
        link.onload = resolve;
        link.onerror = reject;
      });
      document.head.appendChild(link);
      await promise;
    });

    Injecting Raw CSS Content

    await page.evaluate(async () => {
      const style = document.createElement('style');
      style.type = 'text/css';
      const content = `
        #example {
          color: #000;
        }
      `;
      style.appendChild(document.createTextNode(content));
      const promise = new Promise((resolve, reject) => {
        style.onload = resolve;
        style.onerror = reject;
      });
      document.head.appendChild(style);
      await promise;
    });

    Conclusion

    Injecting CSS into a website using Puppeteer is a powerful way to manage and manipulate the DOM during automated testing. By employing methods like page.addStyleTag, page.evaluateOnNewDocument, and page.evaluate, you can ensure that your tests run smoothly without interference from obstructive elements.

    For those looking to streamline their mobile app testing processes, consider using Repeato, a no-code test automation tool for iOS and Android. Repeato allows you to create, run, and maintain automated tests quickly using computer vision and AI. Whether you’re a beginner or an advanced tester, Repeato’s intuitive test recorder and scripting interface can help you automate complex use cases efficiently. Learn more about Repeato’s capabilities here.

    Like this article? there’s more where that came from!