Skip to content
Advertisement

Injecting CSS into site with Puppeteer

The site I’m running automated tests on with Puppeteer displays info popups if actions were successful or when something failed. Unfortunately, these popups sometimes cover up buttons my script has to click on. It would be great if I could inject some CSS into the site to hide these popups. Is there an built-in way to do this?

Advertisement

Answer

addStyleTag:

You can use page.addStyleTag to add some style which will either add a link or style tag based on your options which can be a url, path or some css content.

// url
await page.addStyleTag({url: 'http://example.com/style.css'})

// path, can be relative or absolute path
await page.addStyleTag({path: 'style.css'})

// content
await page.addStyleTag({content: '.body{background: red}'})

evaluateOnNewDocument:

If you want to apply on each page/navigation, you can use page.evaluateOnNewDocument with this snippet.

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