I'm trying to inject a line of css into a pages html code everytime right after navigation happens.
await page.evaluateOnNewDocument(()=>{
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.popover{display: none !important}';
let element = document.getElementById('popover-background');
element.append(style);
});
Doing it like that, I get an error saying that the function 'append' cannot be called on element because element is null.
I also tried to append the style element as a child in the head element using document.getElementsByTagName('head')
. The result was even weirder:
The returned HTMLCollection did include the head element at index 0 and everything associated with it. I could look into it in the chromium console, the object was there, and also its innerHTML and stuff. But when I tried to access it using elements[0] or elements.item(0), it always returned null or undefined. elements[0] returns undefined, elements.item(0) returns null.
the following line resulted in an error saying that appendChild() can't be called on undefined:
document.getElementsByTagName('head')[0].appendChild(style);
Any ideas?
Sorry If I cant answer in comments(newbie here), but as far as I get it, the problem there is that the element is not renderer inside the function, so you should wait for it and then use the document.getElementById.
Also You can try this =>
await page.evaluateOnNewDocument(()=>{
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.popover{display: none !important}';
setTimeout(()=>{
let element = document.getElementById('popover-background');
element.append(style);
}, 1000);
});