File: evaluating.md | Updated: 11/18/2025
On this page
Introduction
Playwright scripts run in your Playwright environment. Your page scripts run in the browser page environment. Those environments don't intersect, they are running in different virtual machines in different processes and even potentially on different computers.
The page.evaluate()
API can run a JavaScript function in the context of the web page and bring results back to the Playwright environment. Browser globals like window and document can be used in evaluate.
Sync
Async
href = page.evaluate('() => document.location.href')
href = await page.evaluate('() => document.location.href')
If the result is a Promise or if the function is asynchronous evaluate will automatically wait until it's resolved:
Sync
Async
status = page.evaluate("""async () => { response = await fetch(location.href) return response.status}""")
status = await page.evaluate("""async () => { response = await fetch(location.href) return response.status}""")
Different environments
Evaluated scripts run in the browser environment, while your test runs in a testing environments. This means you cannot use variables from your test in the page and vice versa. Instead, you should pass them explicitly as an argument.
The following snippet is WRONG because it uses the variable directly:
Sync
Async
data = "some data"result = page.evaluate("""() => { // WRONG: there is no "data" in the web page. window.myApp.use(data)}""")
data = "some data"result = await page.evaluate("""() => { // WRONG: there is no "data" in the web page. window.myApp.use(data)}""")
The following snippet is CORRECT because it passes the value explicitly as an argument:
Sync
Async
data = "some data"# Pass |data| as a parameter.result = page.evaluate("""data => { window.myApp.use(data)}""", data)
data = "some data"# Pass |data| as a parameter.result = await page.evaluate("""data => { window.myApp.use(data)}""", data)
Evaluation Argument
Playwright evaluation methods like page.evaluate() take a single optional argument. This argument can be a mix of Serializable values and JSHandle instances. Handles are automatically converted to the value they represent.
Sync
Async
Init scripts
Sometimes it is convenient to evaluate something in the page before it starts loading. For example, you might want to setup some mocks or test data.
In this case, use page.add_init_script()
or browser_context.add_init_script()
. In the example below, we will replace Math.random() with a constant value.
First, create a preload.js file that contains the mock.
// preload.jsMath.random = () => 42;
Next, add init script to the page.
Sync
Async