Whenever I try to pass a function, like this:
var myFunc = function() { console.log("lol"); }; await page.evaluate(func => { func(); return true; }, myFunc);
I get:
(node:13108) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Evaluation failed: TypeError: func is not a function at func (<anonymous>:9:9) (node:13108) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Why? How to do it correctly?
Thank you!
€: let me clarify: I am doing it this way because I want to find some DOM elements first and use them inside of that function, more like this (simplified):
var myFunc = function(element) { element.innerHTML = "baz" }; await page.evaluate(func => { var foo = document.querySelector('.bar'); func(foo); return true; }, myFunc);
You cannot pass a function directly into page. evaluate() , but you can call another special method ( page. exposeFunction ), which expose your function as a global function (also available in as an attribute of your page window object), so you can call it when you are inside page.
evaluate, returns a Promise, then frame. evaluate would wait for the promise to resolve and return its value. If the function passed into frame. evaluate returns a non-Serializable value, then frame. evaluate resolves to undefined.
You cannot pass a function directly into page.evaluate()
, but you can call another special method (page.exposeFunction
), which expose your function as a global function (also available in as an attribute of your page window
object), so you can call it when you are inside page.evaluate()
:
var myFunc = function() { console.log("lol"); }; await page.exposeFunction("myFunc", myFunc); await page.evaluate(async () => { await myFunc(); return true; });
Just remember that page.exposeFunction()
will make your function return a Promise
, then, you need to use async
and await
. This happens because your function will not be running inside your browser, but inside your nodejs
application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With