为什么我不能使用Puppeteer在暴露函数()中访问“窗口"?
我有一个非常简单的木偶脚本,该脚本使用
I have a very simple Puppeteer script that uses exposeFunction()
to run something inside headless Chrome.
(async function(){
var log = console.log.bind(console),
puppeteer = require('puppeteer');
const browser = await puppeteer.launch();
const page = await browser.newPage();
var functionToInject = function(){
return window.navigator.appName;
}
await page.exposeFunction('functionToInject', functionToInject);
var data = await page.evaluate(async function(){
console.log('woo I run inside a browser')
return await functionToInject();
});
console.log(data);
await browser.close();
})()
此操作失败,并显示以下信息:
This fails with:
ReferenceError: window is not defined
指的是注入函数.如何在无头Chrome中访问window
?
Which refers to the injected function. How can I access window
inside the headless Chrome?
我知道我可以代替evaluate()
,但这不适用于我动态传递的函数:
I know I can do evaluate()
instead, but this doesn't work with a function I pass dynamically:
(async function(){
var log = console.log.bind(console),
puppeteer = require('puppeteer');
const browser = await puppeteer.launch();
const page = await browser.newPage();
var data = await page.evaluate(async function(){
console.log('woo I run inside a browser')
return window.navigator.appName;
});
console.log(data);
await browser.close();
})()
exposeFunction()
不是适合此工作的工具.
exposeFunction()
isn't the right tool for this job.
从木偶文档 >
page.exposeFunction(name,puppeteerFunction)
page.exposeFunction(name, puppeteerFunction)
puppeteerFunction回调函数,将在Puppeteer的上下文中称为 .
puppeteerFunction Callback function which will be called in Puppeteer's context.
在伪造者的上下文中"有点模糊,但请查看evaluate()
的文档:
'In puppeteer's context' is a little vague, but check out the docs for evaluate()
:
page.evaluateHandle(pageFunction,... args)
page.evaluateHandle(pageFunction, ...args)
pageFunction要在页面上下文中评估的功能
pageFunction Function to be evaluated in the page context
exposeFunction()
不会公开要在页面内运行的函数,但是会公开要在页面的节点中运行的函数.
exposeFunction()
doesn't expose a function to run inside the page, but exposes a function to be be run in node to be called from the page.
我必须使用evaluate()
: