fix(web): evaluate a browser.evaluate string as an expression

Merged
OK
2mo ago
+51-4

browser.evaluate with a string always called it as a function: (${source})(arg). Anything but function source failed.

  • browser.evaluate('(() => document.title)()') failed with EVALUATE_FAILED: (intermediate value)(...) is not a function; browser.evaluate('document.title') with document.title is not a function.
  • A string is now evaluated as a single expression: a function it evaluates to is called with arg (kept for existing '() => ...' strings; Playwright would return the function), any other value is the result, a promise awaited (packages/web/src/evaluation.ts:29).
  • Statements ('a(); b()', a trailing ;) still fail with EVALUATE_FAILED. Supporting them means an eval in the page, which page CSP can block and which loses the __name helper; docs say "single expression".
  • No new binding is visible to the source, so a page global named result or value still reads through.
  • Function arguments are serialized with toString() and go through the same path, so they behave as before.
  • Docs: reference/web.mdx evaluate section and the method JSDoc say what a string means.
await browser.evaluate('document.title');            // 'Playground'
await browser.evaluate('(() => document.title)()');  // 'Playground'
await browser.evaluate('() => document.title');      // 'Playground', unchanged

Verified

Ran it locally: yes

  • testbed, built CLI, one test per string, logging the result:
sourcemainthis branch
'document.title'EVALUATE_FAILED: document.title is not a function"Playground"
'(() => document.title)()'EVALUATE_FAILED: (intermediate value)(...) is not a function"Playground"
'() => document.title'"Playground""Playground"
  • New unit and integration cases fail on main (4 failures) and pass here.