Answer
page.evaluate() in Playwright
page.evaluate() runs a JavaScript function inside the browser and returns the result back to your Node.js test code.
Basic Usage
TypeScript
// Execute JS and get the return value
const title = await page.evaluate(() => document.title);
console.log(title); // "My App"
// Get page URL
const url = await page.evaluate(() => window.location.href);
// Get a computed style
const color = await page.evaluate(() => {
const el = document.querySelector('.header');
return window.getComputedStyle(el!).color;
});
Passing Arguments to evaluate()
TypeScript
// Pass values from Node.js into the browser function
const selector = '.product-card';
const count = await page.evaluate((sel) => {
return document.querySelectorAll(sel).length;
}, selector);
// Pass multiple values using an object
const result = await page.evaluate(({ name, age }) => {
return `${name} is ${age}`;
}, { name: 'John', age: 30 });
Common Use Cases
Read localStorage / sessionStorage
TypeScript
const token = await page.evaluate(() => localStorage.getItem('auth_token'));
const session = await page.evaluate(() => sessionStorage.getItem('user_id'));
Set localStorage (Setup for tests)
TypeScript
await page.evaluate(token => {
localStorage.setItem('auth_token', token);
}, 'my-test-token-123');
Scroll to Element or Position
TypeScript
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
await page.evaluate(selector => {
document.querySelector(selector)?.scrollIntoView();
}, '#footer');
Read Cookie (not httpOnly ones)
TypeScript
const cookie = await page.evaluate(() => document.cookie);
Trigger Custom Events
TypeScript
await page.evaluate(() => {
window.dispatchEvent(new Event('storage'));
});
Force Hide Element
TypeScript
await page.evaluate(selector => {
const el = document.querySelector(selector) as HTMLElement;
if (el) el.style.display = 'none';
}, '.cookie-banner');
page.evaluate() vs page.evaluateHandle()
evaluate() | evaluateHandle() | |
|---|---|---|
| Returns | Serialized JS value (JSON) | A handle to a JS object |
| Use when | Need a primitive/plain object | Need to keep a DOM element reference |
TypeScript
// evaluateHandle — returns a JSHandle to a DOM element
const element = await page.evaluateHandle(() => document.querySelector('h1'));
await element.asElement()?.click();
Limitations
- ✓Only JSON-serializable values can be returned by
evaluate() - ✓Cannot return DOM elements directly (use
evaluateHandle()for that) - ✓Runs in the browser context — no access to Node.js
fs,path, etc.
