乐闻世界logo
搜索文章和话题

How to stop all JS scripts in Puppeteer

1个答案

1

When using Puppeteer for web automation, it may sometimes be necessary to block the execution of all JavaScript scripts on a page to speed up page loading or prevent certain operations. This can be achieved through the following steps:

  1. Intercept Requests: Enable request interception by calling page.setRequestInterception(true) in Puppeteer.
  2. Analyze Requests: In the request interceptor, check the type of each network request.
  3. Terminate JS File Requests: If the request type is 'script', use request.abort() to block the request, thereby preventing the download and execution of the related JavaScript files.
  4. Allow Other Requests: For other request types that are not scripts, use request.continue() to allow them to proceed normally.

Here is an example implementation using Puppeteer:

javascript
const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); // Enable request interception await page.setRequestInterception(true); // Add request interceptor page.on('request', (request) => { // If it's a script file, terminate the request if (request.resourceType() === 'script') { request.abort(); } else { // Other request types continue normally request.continue(); } }); // Navigate to a webpage await page.goto('http://example.com'); // Other page operations... // Close the browser await browser.close(); })();

Using this method, all JavaScript script requests will be blocked. However, this does not prevent inline or pre-executed scripts on the page from being executed. To block inline scripts or JavaScript that has already been executed, different strategies are needed, such as injecting custom scripts before page load to disable or override functions like eval and other JavaScript execution functions.

For example, you can disable inline scripts before page load with the following code:

javascript
await page.evaluateOnNewDocument(() => { window.eval = global.eval = function() { throw new Error(`Eval is disabled`); }; });

Overall, depending on your specific needs, you can choose the appropriate method to stop JavaScript scripts from executing on Puppeteer-controlled pages.

2024年6月29日 12:07 回复

你的答案