Injecting CSS into site with Puppeteer
page.evaluate()
Stylesheet:
You can use page.evaluate()
to inject a stylesheet into the current page using the following method:
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;
});
Raw CSS Content:
Alternatively, you can also use page.evaluate()
to inject raw CSS into the current page:
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;
});
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);
});