木偶:如何将对象传递给page.evaluate?

时间:2019-03-15 06:39:26

标签: javascript node.js puppeteer

我试图将自定义对象传递给page.evaluate(),但是当我运行脚本时,它将引发以下错误:

Error: Evaluation failed: TypeError: Cannot read property 'p1' of undefined

如何在浏览器上下文中使用自定义对象?

const puppeteer = require('puppeteer');

function obj() {
    this.p1 = 'a';
    this.p2 = {
        p21: 'b'
    };
};

(async function () {
    try {
        const browser = await puppeteer.launch();
        const page = await browser.newPage();
        await page.goto('https://stackoverflow.com/');

        page.on('console', consoleObj => console.log(consoleObj.text()));

        const obj1 = new obj();

        await page.evaluate((obj1) => {
            console.log(obj1.p1);
            console.log(obj1.p2.p21);
            console.log(obj1.p2.p21);
        });

        browser.close();
    } catch (e) {
        console.log(e);
    };
})();

1 个答案:

答案 0 :(得分:3)

您可以传递如下对象,

await page.evaluate((obj) => { // <-- use it as parameter of this function
            console.log(obj.p1); // <-- use it inside as you wish 
            console.log(obj.p2.p21);
            console.log(obj.p2.p21);
}, obj); //<-- pass it here as argument

请记住,您传递的对象将被序列化,因此圆形对象或函数等将不起作用。