Puppeteer:如何将对象传递到page.evaluate?

5
我试图将自定义对象传递给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个回答

14
你可以像以下这样传递一个对象,
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

请记住所传递的对象将会被序列化,因此循环引用的对象或函数等将无法正常使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接