◐ Shell
clean mode source ↗

Evaluating JavaScript | Playwright Python

# A primitive value.

page.evaluate('num => num', 42)

# An array.

page.evaluate('array => array.length', [1, 2, 3])

# An object.

page.evaluate('object => object.foo', { 'foo': 'bar' })

# A single handle.

button = page.evaluate_handle('window.button')

page.evaluate('button => button.textContent', button)

# Alternative notation using JSHandle.evaluate.

button.evaluate('(button, from) => button.textContent.substring(from)', 5)

# Object with multiple handles.

button1 = page.evaluate_handle('window.button1')

button2 = page.evaluate_handle('.button2')

page.evaluate("""o => o.button1.textContent + o.button2.textContent""",

{ 'button1': button1, 'button2': button2 })

# Object destructuring works. Note that property names must match

# between the destructured object and the argument.

# Also note the required parenthesis.

page.evaluate("""

({ button1, button2 }) => button1.textContent + button2.textContent""",

{ 'button1': button1, 'button2': button2 })

# Array works as well. Arbitrary names can be used for destructuring.

# Note the required parenthesis.

page.evaluate("""

([b1, b2]) => b1.textContent + b2.textContent""",

[button1, button2])

# Any mix of serializables and handles works.

page.evaluate("""

x => x.button1.textContent + x.list[0].textContent + String(x.foo)""",

{ 'button1': button1, 'list': [button2], 'foo': None })