Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop all JS scripts in Puppeteer

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)

like image 362
RexFuzzle Avatar asked Aug 17 '18 14:08

RexFuzzle


Video Answer


3 Answers

const page = await browser.newPage()
page.setJavaScriptEnabled(false)
like image 57
Vimal Joseph Avatar answered Oct 15 '22 02:10

Vimal Joseph


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);
like image 39
Grant Miller Avatar answered Oct 15 '22 03:10

Grant Miller


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

like image 27
Julien Le Coupanec Avatar answered Oct 15 '22 04:10

Julien Le Coupanec