Rayrun
← Back to Discord Forum

Passing functions into $$eval

Is passing functions into $$eval possible? I know that you can add argument to the pageFunction, but if I am passing function, playwright will just go "Error: Unexpected value"

This thread is trying to answer question "Is it possible to pass functions into $$eval in Playwright?"

12 replies
function hello(): string {
    return "world";
}
 
page.$$eval("something", (items, fn) => {
    return fn();
}, hello);

this should work right? except that I got Error: Unexpected value

If I pass something like object, string, numbers it worked, but not functions

I am trying to reduce code duplications

I think the $$eval is from ElementHandle which is deprecated. Playwright encourages to use Locator instead. https://playwright.dev/docs/api/class-elementhandle

refactoreric

Indeed, it's better to use Locator. Using element handles is discouraged. Element handles are much less stable/less flake resistant.

So instead of page.$$eval, this is the better option: https://playwright.dev/docs/api/class-locator#locator-evaluate-all

Passing functions like this from NodeJS execution context to the browser execution context does not work. What we pass as arguments needs to be serializable.

If you want to have functions in the browser execution context which call code in the NodeJS execution context, then you can use this: https://playwright.dev/docs/api/class-page#page-expose-function

I just migrated to Locator

but yes still doesn't work

I am currently doing toString() on my function then do eval("(${func})") to restore it

@refactoreric: interesting, expose function huh

interesting, expose function huh

it's not typescript friendly tho

well not a problem

Related Discord Threads

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].