puppeteer: async function inside evaluate fails
Code
await page.evaluate(async () => {
console.log('1')
})
Error
(node:66796) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Evaluation failed: ReferenceError: fn is not defined
at <anonymous>:1:26
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Reactions: 16
- Comments: 16 (6 by maintainers)
Commits related to this issue
- docs(troubleshooting): add workarounds for code transpilation (#3399) References #1665 — committed to puppeteer/puppeteer by cancerberoSgx 6 years ago
- fix(page.evaluate): better function serialization (#3480) References #1665 — committed to puppeteer/puppeteer by aslushnikov 6 years ago
Are you transforming your code with babel? The babel async function code isn’t compatible with Puppeteer. We call
function.toString
and send your code into Chromium, but babel messes with that and we end up sending an incomplete string. You can get around this by using template strings instead of functions.same issue, different error, using TypeScript (not babel). The solution for me was to instruct TypeScript to compile to latest ecma version so no pollyfills / artificial code is generated for async function support, in tsconfig.json file:
issue details
While the following works OK:
the equivalent code using async functions throws the following error:
Error:
puppeteer v1.0.0-rc ( git://github.com/GoogleChrome/puppeteer.git#fc2fc0d ) centos-release-7-3.1611.el7.centos.x86_64
Hi, I’m trying to use with Echart library to generate and get its based64 image.
However the base64img is undefined. Is there any solution to make it works perfectly with Babel?
@jtara1: we made our serialization logic more clever so that it doesn’t bite you next time. We’ll update our docs to explain the function serialization.
You can’t import something from Node and use it in Chromium. You have to navigate Chromium to a webpage that includes your utility script.
@reservce - This solution works great! But I agree, it’s obviously not a true solution (after all, a template string is technically just a string, though it will get eval’ed as actual code…)
As a side question: How did you know to do this, or figure out how to do this?
@yujiosaka not sure what would be the good place in the docs. There’s been quite a bit discussion on babel on the bugtracker, so it should be searchable now.
Speculatively closing this since the issue seems to be related to transpilation.