为什么我不能使用Puppeteer在暴露函数()中访问“窗口"? [英] Why can't I access 'window' in an exposeFunction() function with Puppeteer?

查看:386
本文介绍了为什么我不能使用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():

这篇关于为什么我不能使用Puppeteer在暴露函数()中访问“窗口"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆