Puppeter and Playwright both offer a Page.exposeFunction enabling you to set globals to the window object and call them.
Playwright also has a Page.exposeBinding, though I'm less sure what's distinct there, as well as equivalents to both for the larger BrowserContext.
I'm still having trouble getting function definitions passed in manually from outside, but I can confirm that assigning to window will persist across page.evaluate calls:
But, it only works with arrow functions. Using function -- whether on its own or with const -- you have to isolate the code block and its arguments separately, and then pass them into Function. For a simple example without arguments:
Puppeter and Playwright both offer a
Page.exposeFunction
enabling you to set globals to thewindow
object and call them.Playwright also has a
Page.exposeBinding
, though I'm less sure what's distinct there, as well as equivalents to both for the largerBrowserContext
.I'm still having trouble getting function definitions passed in manually from outside, but I can confirm that assigning to
window
will persist acrosspage.evaluate
calls:That said it's partly an issue getting plain and arrow functions to consistently type coerce to and from strings. The below does work:
But, it only works with arrow functions. Using
function
-- whether on its own or withconst
-- you have to isolate the code block and its arguments separately, and then pass them intoFunction
. For a simple example without arguments:Both
eval
andFunction
also don't work by default using Firefox, even on the New Tab page