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();
})();