我试图将我的自定义对象传递给 page.evaluate()
,但是当我运行脚本时它抛出以下错误:
错误:评估失败:TypeError:无法读取未定义的属性“p1”
。
如何在浏览器上下文中使用自定义对象?
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);
};
})();
最佳答案
你可以像下面这样传递一个对象,
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
请记住,您传递的对象将被序列化,因此循环对象或函数等将不起作用。
关于javascript - Puppeteer:如何将对象传递给 page.evaluate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55176943/