How can I pass a variable into an evaluate function?
To inject a variable into page.evaluate
in Puppeteer, pass it as the second argument for the function. This sequence transfers the value from your Node.js environment to the paginated browser context:
Handling multiple variables
Handling multiple variables? No problem, just provide additional arguments:
Dealing with complex data types
For non-serializable objects or functions, use JSHandles or serialization:
Or serialize like a boss:
Debugging cues
To debug within page.evaluate
, use debugger;
- it's literally a debug keyword:
Remember to set { devtools: true }
on launch, unless you're fond of Schroedinger's bug.
Console output and headless mode
Keep in mind, console.log()
in page.evaluate()
won't print in Node.js (they don't have that kind of relationship yet.) In headless mode, listen to the page.on('console')
event:
Scoping, serialization, and you
Serialization can behave like a boomerang with spikes if your variable includes functions or symbolic keys (JSON gives them the cold shoulder). Be careful with such variables! Stringify functions or use JSHandles to keep things smooth.
Case studies: Beyond the basics
Curious about object destructuring, explicit global function definition, or working in different browser contexts?
Pitfalls and parachutes
Going headfirst into scripting? Watch for these common pitfalls:
- Scoping: Remember, what's declared outside of
page.evaluate
doesn't exist inside it unless you pass it as an argument. - Serialization: If your variable can't be serialized, expect errors. Meanwhile,
JSON.stringify
andJSHandles
wait patiently by your side. - Event listeners: Those lovely events within
page.evaluate
? They're browser-scoped. Node.js can't hear them directly.
Was this article helpful?