admin管理员组文章数量:1334282
In Puppeteer, page.evaluate
throws an error if I pass a class as an argument.
It works for regular objects though.
Is there some workaround to make it work?
const puppeteer = require("puppeteer");
(async () => {
let browser = await puppeteer.launch({
headless: true
});
let page = await browser.newPage();
class SomeClass {
constructor() {
this.a = 3;
}
}
await page.evaluate((SomeClass) => {
let object = new SomeClass();
console.log(object.a);
}, SomeClass);
})();
In Puppeteer, page.evaluate
throws an error if I pass a class as an argument.
It works for regular objects though.
Is there some workaround to make it work?
const puppeteer = require("puppeteer");
(async () => {
let browser = await puppeteer.launch({
headless: true
});
let page = await browser.newPage();
class SomeClass {
constructor() {
this.a = 3;
}
}
await page.evaluate((SomeClass) => {
let object = new SomeClass();
console.log(object.a);
}, SomeClass);
})();
Share
Improve this question
edited Jul 16, 2018 at 17:36
Grant Miller
29.1k16 gold badges155 silver badges168 bronze badges
asked Jul 16, 2018 at 6:59
yewangyewang
6451 gold badge8 silver badges18 bronze badges
1
- Answer depends on how would you evaluate a class? Define that and edit the question to include this information and I'll help you reach a working solution – Adelin Commented Jul 16, 2018 at 7:03
2 Answers
Reset to default 7There is a similar problem if you try to pass a function. I've seen people stringifying the function to pass it to puppeteer to make it work, so in your case I'd do this using eval. Many people think eval is evil, maybe there is a better way, but at least it's a possible workaround.
class SomeClass {
constructor() {
this.a = 3;
}
}
await page.evaluate((strSomeClass) => {
eval("window.SomeClass = " + strSomeClass);
let object = new SomeClass();
console.log(object.a);
}, SomeClass.toString());
You can avoid using eval()
by passing an instance of the object, rather then the object itself, to page.evaluate()
:
await page.evaluate(object => {
console.log(object.a);
}, new SomeClass);
Your full program should look something like this:
'use strict';
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({
headless: true,
});
const page = await browser.newPage();
class SomeClass {
constructor() {
this.a = 3;
}
}
await page.evaluate(object => {
console.log(object.a);
}, new SomeClass);
await browser.close();
})();
本文标签: javascriptPass Class as an Argument to pageevaluate in PuppeteerStack Overflow
版权声明:本文标题:javascript - Pass Class as an Argument to page.evaluate in Puppeteer - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742371571a2462342.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论