gpt4 book ai didi

node.js - 在加载页面之前是否有 PhantomJS onInitialized 的 Puppeteer 替代品来评估?

转载 作者:搜寻专家 更新时间:2023-11-01 00:36:39 26 4
gpt4 key购买 nike

我有一个程序正在使用 PhantomJS onInitialized方法来设置页面首次加载时可以使用的窗口全局变量。我还没有找到用 puppeteer 做到这一点的方法。在创建页面之后但在转到页面之前调用 evaluate 会重置变量。在 domcontentloaded 中执行它似乎为时已晚。

  const browser = await puppeteer.launch();
const page = await browser.newPage();

await page.evaluate(pageParams => {
window.sharedConfig = 1; // Sets it but gets reset when the page loads
}, pageParams);

page.on('domcontentloaded', msg => {
page.evaluate(pageParams => {
window.sharedConfig = 2; // Sets it but it's too late
}, pageParams);
});

let pageResult = await page.goto(url);

await page.evaluate(pageParams => {
window.sharedConfig = 3; // Def too late
}, pageParams);

最佳答案

我认为 PhantomJS 的等效 API onInitialized 实际上是通过 Browser :: targetcreated 实现的事件:

Emitted when a target is created, for example when a new page is opened by window.open or browser.newPage.

为所有新创建的页面初始化 window.sharedConfig 的示例:

(async () => {
const browser = await puppeteer.launch();

browser.on('targetcreated', async target => {
const page = await target.page();
await page.evaluate(() => {
window.sharedConfig = 0;
});
});

const page = browser.newPage();
await page.evaluate(() => console.log(window.sharedConfig)); // => 0

await browser.close();
})();

如果您需要在导航时设置额外的页面,您可以使用 page.evaluateOnNewDocument() :

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.

初始化 window.sharedConfig 然后在页面导航上更改初始值的示例:

(async () => {
const browser = await puppeteer.launch();

browser.on('targetcreated', async target => {
const page = await target.page();

// Initialize window.sharedConfig for new page
await page.evaluate(() => {
window.sharedConfig = 0;
});

// Set window.sharedConfig when the page is navigated (before page loads)
await page.evaluateOnNewDocument(() => {
// window.sharedConfig === 0
window.sharedConfig = 1;
});
});

const page = browser.newPage();
await page.evaluate(() => console.log(window.sharedConfig)); // => 0
await page.goto('http://google.com');
await page.evaluate(() => console.log(window.sharedConfig)); // => 1

await browser.close();
})();

关于node.js - 在加载页面之前是否有 PhantomJS onInitialized 的 Puppeteer 替代品来评估?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49243149/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com