预备JS执行环境,预执行脚本

Posted FromScratch

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了预备JS执行环境,预执行脚本相关的知识,希望对你有一定的参考价值。

page.evaluateOnNewDocument(pageFunction, ...args)

Adds a function which would be invoked in one of the following scenarios:

  • whenever the page is navigated
  • whenever the child frame is attached or navigated. In this case, the function is invoked in the context of the newly attached frame

The function is invoked after the document was created but before any of its scripts were run. This is useful to amend the javascript environment, e.g. to seed Math.random.

 

// overwrite the `languages` property to use a custom getter
Object.defineProperty(navigator, "languages", {
  get: function() {
    return ["en-US", "en", "bn"];
  }
});

// In your puppeteer script, assuming the preload.js file is in same folder of our script
const preloadFile = fs.readFileSync(‘./preload.js‘, ‘utf8‘);
await page.evaluateOnNewDocument(preloadFile);

以上是关于预备JS执行环境,预执行脚本的主要内容,如果未能解决你的问题,请参考以下文章

js作用域其二:预解析

javascript预解析和作用域

[js]js栈内存的全局/私有作用域,代码预解释

js对代码解析机制

JavaScript预编译

JavaScript进阶之执行上下文和执行栈