Reputation: 2203
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?
Upvotes: 32
Views: 34875
Reputation: 18826
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}'})
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);
});
Upvotes: 81
Reputation: 523
await page.$eval('.popup', el => el.style.display = "none")
Upvotes: -1
Reputation: 11
You can use
// add css
const contents = '<table class="class4" style="width: 100%;">
<tbody>
<tr>
<td style="width: 33.3333%;" class="">
<br></td>
<td style="width: 33.3333%;">
<br></td>
<td style="width: 33.3333%;">
<br></td>
</tr>
</tbody>
</table>'
// add css
const cssStyle = `<style>
.class4 thead tr th,.class4 tbody tr td {
border-style: solid;
border-color: coral;
border-width: 1px;
}
</style>
`;
// add css
const addCssContent = cssStyle + contents;
await page.goto(`data:text/html;base64;charset=UTF-8,${Buffer.from(addCssContent).toString(
"base64"
)}`,
{
waitUntil: "load",
timeout: 300000,
waitFor: 30000,
}
);
Upvotes: 1
Reputation: 29019
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;
});
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;
});
Upvotes: 4