I would like to be able to stop any scripts from being able to run in puppeteer after the page has loaded. The reason for this is to stop carousel images and lazy loading images and essentially get the page to behave as statically as possible to enable screenshots where the images aren't changing etc.
By doing page.evaluate('debugger;')
it is possible to pause the whole script, but this does not let you continue with taking screen shots as the a evaluate
function does not exit until you exit the debugger (If the gui is enabled)
const page = await browser.newPage()
page.setJavaScriptEnabled(false)
If you would like to disable JavaScript after the page has loaded, you can use debugger
:
await page.evaluate(() => {
debugger;
});
I was able to take screenshots after using the debugger.
Alternatively, you can replace each original node with its clone to remove the events attached to each element:
await page.evaluate(() => {
document.querySelectorAll('*').forEach(element => {
element.parentNode.replaceChild(element.cloneNode(true), element);
});
});
You can also use removeEventListener()
in a loop similar to the one above to remove specific events attached to a node.
Otherwise, if you can disable JavaScript before the page has loaded, you can use page.setJavaScriptEnabled()
before navigating to the page:
await page.setJavaScriptEnabled(false);
A better solution is just to block all requests with the type equals to script
:
const puppeteer = require("puppeteer");
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on("request", request => {
if (request.resourceType() === "script") {
request.abort()
} else {
request.continue()
}
})
await page.goto("https://stackoverflow.com/")
await browser.close()
})()
Source: Disabling JavaScript Using Puppeteer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With