All challenges · Advanced Techniques
Challenge 17 of 29 · Stretch skills · Advanced Techniques
Run JavaScript in the Browser
Run a small script inside the page to read and change it, using a value that is only known while the test runs.
Skills you will practise
- page.evaluate
- browser context
- values known only at run time
The concept
Your Playwright test runs in Node.js, but the page runs in the browser. They are separate worlds. page.evaluate() lets you send a function into the browser, run it there with access to document and window, and get a serialisable result back.
Because the function runs in the browser, it cannot see variables from your test file. If you need a value that only exists at run time, such as a generated ID or a random name, pass it as the second argument. Playwright serialises it and hands it to your function.
Use evaluate sparingly. For clicking and typing, real Playwright actions are better because they behave like a user and auto-wait. evaluate is for reading state, setting things up, or checking values the UI does not show.
The fragile version
const name = `user-${Date.now()}`;
await page.evaluate(() =>
document.querySelector('.display-name').textContent = name
);Why it breaks: name exists in Node, not the browser, so this throws ReferenceError: name is not defined inside the page.
A robust Playwright version
const name = `user-${Date.now()}`;
await page.evaluate(value => {
document.querySelector('.display-name').textContent = value;
}, name);
expect(await page.evaluate(() => document.title)).toContain('Profile');The run-time value is passed explicitly, and the return value comes back to the test.
This is a general example on a made-up page, not the challenge’s reference solution.
Common mistakes
- Referencing test-scope variables inside the evaluate function.
- Returning DOM nodes or functions, which cannot be serialised; return plain data.
- Using
evaluateto click things instead of Playwright actions.
FAQ
Can page.evaluate use variables from my test?
Only if you pass them as the argument. The function runs in the browser.
What can page.evaluate return?
Serialisable values such as strings, numbers, arrays and plain objects. Use evaluateHandle for live objects.
Should I click with evaluate?
Generally no; locator.click() is more realistic and auto-waits.
Try it
Practise this in Challenge 17. You write the code in the browser editor with no setup. It runs in a fresh Chromium, a hidden validator checks what actually happened, and you get pass or fail, the logs and a video of the run. Create a free account to open the practice page and its hints. The reference solution and the hidden validator are shown only after you pass. We never publish solutions here.