Class: Playwright::Page

Inherits:
PlaywrightApi show all
Defined in:
lib/playwright_api/page.rb,
sig/playwright.rbs

Overview

Page provides methods to interact with a single tab in a Browser, or an extension background page in Chromium. One Browser instance might have multiple Page instances.

This example creates a page, navigates it to a URL, and then saves a screenshot:

from playwright.sync_api import sync_playwright, Playwright

def run(playwright: Playwright):
    webkit = playwright.webkit
    browser = webkit.launch()
    context = browser.new_context()
    page = context.new_page()
    page.goto("https://example.com")
    page.screenshot(path="screenshot.png")
    browser.close()

with sync_playwright() as playwright:
    run(playwright)

The Page class emits various events (described below) which can be handled using any of Node's native EventEmitter methods, such as on, once or removeListener.

This example logs a message for a single page load event:

page.once("load", lambda: print("page loaded!"))

To unsubscribe from events use the removeListener method:

def log_request(intercepted_request):
    print("a request was made:", intercepted_request.url)
page.on("request", log_request)
# sometime later...
page.remove_listener("request", log_request)

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from PlaywrightApi

#initialize, unwrap, wrap

Constructor Details

This class inherits a constructor from Playwright::PlaywrightApi

Instance Attribute Details

#clockClock (readonly)

Playwright has ability to mock clock and passage of time.

Returns:



48
49
50
# File 'lib/playwright_api/page.rb', line 48

def clock # property
  wrap_impl(@impl.clock)
end

#keyboardKeyboard (readonly)

property

Returns:



52
53
54
# File 'lib/playwright_api/page.rb', line 52

def keyboard # property
  wrap_impl(@impl.keyboard)
end

#local_storageWebStorage (readonly)

Provides access to the page's localStorage for the current origin. See WebStorage.

Returns:



58
59
60
# File 'lib/playwright_api/page.rb', line 58

def local_storage # property
  wrap_impl(@impl.local_storage)
end

#mouseMouse (readonly)

property

Returns:



68
69
70
# File 'lib/playwright_api/page.rb', line 68

def mouse # property
  wrap_impl(@impl.mouse)
end

#requestAPIRequestContext (readonly)

API testing helper associated with this page. This method returns the same instance as [property: BrowserContext.request] on the page's context. See [property: BrowserContext.request] for more details.

Returns:



75
76
77
# File 'lib/playwright_api/page.rb', line 75

def request # property
  wrap_impl(@impl.request)
end

#screencastObject (readonly)

Screencast object associated with this page.

Usage

Returns:

  • (Object)


83
84
85
# File 'lib/playwright_api/page.rb', line 83

def screencast # property
  wrap_impl(@impl.screencast)
end

#session_storageWebStorage (readonly)

Provides access to the page's sessionStorage for the current origin. See WebStorage.

Returns:



64
65
66
# File 'lib/playwright_api/page.rb', line 64

def session_storage # property
  wrap_impl(@impl.session_storage)
end

#touchscreenTouchscreen (readonly)

property

Returns:



87
88
89
# File 'lib/playwright_api/page.rb', line 87

def touchscreen # property
  wrap_impl(@impl.touchscreen)
end

Instance Method Details

#_assertions(timeout, is_not, message) ⇒ Object



1884
1885
1886
# File 'lib/playwright_api/page.rb', line 1884

def _assertions(timeout, is_not, message)
  wrap_impl(@impl._assertions(unwrap_impl(timeout), unwrap_impl(is_not), unwrap_impl(message)))
end

#add_init_script(path: nil, script: nil) ⇒ Object

Adds a script which would be evaluated in one of the following scenarios:

  • Whenever the page is navigated.
  • Whenever the child frame is attached or navigated. In this case, the script is evaluated in the context of the newly attached frame.

The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed Math.random.

Usage

An example of overriding Math.random before the page loads:

# in your playwright script, assuming the preload.js file is in same directory
page.add_init_script(path="./preload.js")

NOTE: The order of evaluation of multiple scripts installed via [method: BrowserContext.addInitScript] and [method: Page.addInitScript] is not defined.

Parameters:

  • path: (String, File) (defaults to: nil)
  • script: (String) (defaults to: nil)

Returns:

  • (Object)


110
111
112
# File 'lib/playwright_api/page.rb', line 110

def add_init_script(path: nil, script: nil)
  wrap_impl(@impl.add_init_script(path: unwrap_impl(path), script: unwrap_impl(script)))
end

#add_locator_handler(locator, handler, noWaitAfter: nil, times: nil) ⇒ Object

When testing a web page, sometimes unexpected overlays like a "Sign up" dialog appear and block actions you want to automate, e.g. clicking a button. These overlays don't always show up in the same way or at the same time, making them tricky to handle in automated tests.

This method lets you set up a special function, called a handler, that activates when it detects that overlay is visible. The handler's job is to remove the overlay, allowing your test to continue as if the overlay wasn't there.

Things to keep in mind:

  • When an overlay is shown predictably, we recommend explicitly waiting for it in your test and dismissing it as a part of your normal test flow, instead of using [method: Page.addLocatorHandler].
  • Playwright checks for the overlay every time before executing or retrying an action that requires an actionability check, or before performing an auto-waiting assertion check. When overlay is visible, Playwright calls the handler first, and then proceeds with the action/assertion. Note that the handler is only called when you perform an action/assertion - if the overlay becomes visible but you don't perform any actions, the handler will not be triggered.
  • After executing the handler, Playwright will ensure that overlay that triggered the handler is not visible anymore. You can opt-out of this behavior with noWaitAfter.
  • The execution time of the handler counts towards the timeout of the action/assertion that executed the handler. If your handler takes too long, it might cause timeouts.
  • You can register multiple handlers. However, only a single handler will be running at a time. Make sure the actions within a handler don't depend on another handler.

NOTE: Running the handler will alter your page state mid-test. For example it will change the currently focused element and move the mouse. Make sure that actions that run after the handler are self-contained and do not rely on the focus and mouse state being unchanged.

For example, consider a test that calls [method: Locator.focus] followed by [method: Keyboard.press]. If your handler clicks a button between these two actions, the focused element most likely will be wrong, and key press will happen on the unexpected element. Use [method: Locator.press] instead to avoid this problem.

Another example is a series of mouse actions, where [method: Mouse.move] is followed by [method: Mouse.down]. Again, when the handler runs between these two actions, the mouse position will be wrong during the mouse down. Prefer self-contained actions like [method: Locator.click] that do not rely on the state being unchanged by a handler.

Usage

An example that closes a "Sign up to the newsletter" dialog when it appears:

# Setup the handler.
def handler():
  page.get_by_role("button", name="No thanks").click()
page.add_locator_handler(page.get_by_text("Sign up to the newsletter"), handler)

# Write the test as usual.
page.goto("https://example.com")
page.get_by_role("button", name="Start here").click()

An example that skips the "Confirm your security details" page when it is shown:

# Setup the handler.
def handler():
  page.get_by_role("button", name="Remind me later").click()
page.add_locator_handler(page.get_by_text("Confirm your security details"), handler)

# Write the test as usual.
page.goto("https://example.com")
page.get_by_role("button", name="Start here").click()

An example with a custom callback on every actionability check. It uses a <body> locator that is always visible, so the handler is called before every actionability check. It is important to specify noWaitAfter, because the handler does not hide the <body> element.

# Setup the handler.
def handler():
  page.evaluate("window.removeObstructionsForTestIfNeeded()")
page.add_locator_handler(page.locator("body"), handler, no_wait_after=True)

# Write the test as usual.
page.goto("https://example.com")
page.get_by_role("button", name="Start here").click()

Handler takes the original locator as an argument. You can also automatically remove the handler after a number of invocations by setting times:

def handler(locator):
  locator.click()
page.add_locator_handler(page.get_by_label("Close"), handler, times=1)

Raises:

  • (NotImplementedError)


1233
1234
1235
# File 'lib/playwright_api/page.rb', line 1233

def add_locator_handler(locator, handler, noWaitAfter: nil, times: nil)
  raise NotImplementedError.new('add_locator_handler is not implemented yet.')
end

#add_script_tag(content: nil, path: nil, type: nil, url: nil) ⇒ ElementHandle

Adds a <script> tag into the page with the desired url or content. Returns the added tag when the script's onload fires or when the script content was injected into frame.

Parameters:

  • content: (String) (defaults to: nil)
  • path: (String, File) (defaults to: nil)
  • type: (String) (defaults to: nil)
  • url: (String) (defaults to: nil)

Returns:



117
118
119
# File 'lib/playwright_api/page.rb', line 117

def add_script_tag(content: nil, path: nil, type: nil, url: nil)
  wrap_impl(@impl.add_script_tag(content: unwrap_impl(content), path: unwrap_impl(path), type: unwrap_impl(type), url: unwrap_impl(url)))
end

#add_style_tag(content: nil, path: nil, url: nil) ⇒ ElementHandle

Adds a <link rel="stylesheet"> tag into the page with the desired url or a <style type="text/css"> tag with the content. Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.

Parameters:

  • content: (String) (defaults to: nil)
  • path: (String, File) (defaults to: nil)
  • url: (String) (defaults to: nil)

Returns:



124
125
126
# File 'lib/playwright_api/page.rb', line 124

def add_style_tag(content: nil, path: nil, url: nil)
  wrap_impl(@impl.add_style_tag(content: unwrap_impl(content), path: unwrap_impl(path), url: unwrap_impl(url)))
end

#aria_snapshot(boxes: nil, depth: nil, mode: nil, timeout: nil) ⇒ String

Captures the aria snapshot of the page. Read more about aria snapshots.

Parameters:

  • boxes: (Boolean) (defaults to: nil)
  • depth: (Integer) (defaults to: nil)
  • mode: ("ai", "default") (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Returns:

  • (String)


1496
1497
1498
# File 'lib/playwright_api/page.rb', line 1496

def aria_snapshot(boxes: nil, depth: nil, mode: nil, timeout: nil)
  wrap_impl(@impl.aria_snapshot(boxes: unwrap_impl(boxes), depth: unwrap_impl(depth), mode: unwrap_impl(mode), timeout: unwrap_impl(timeout)))
end

#bring_to_frontvoid

This method returns an undefined value.

Brings page to front (activates tab).



130
131
132
# File 'lib/playwright_api/page.rb', line 130

def bring_to_front
  wrap_impl(@impl.bring_to_front)
end

#cancel_pick_locatorvoid

This method returns an undefined value.

Cancels an ongoing [method: Page.pickLocator] call by deactivating pick locator mode. If no pick locator mode is active, this method is a no-op.



137
138
139
# File 'lib/playwright_api/page.rb', line 137

def cancel_pick_locator
  wrap_impl(@impl.cancel_pick_locator)
end

#check(selector, force: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) ⇒ void

This method returns an undefined value.

This method checks an element matching selector by performing the following steps:

  1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
  2. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already checked, this method returns immediately.
  3. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
  4. Scroll the element into view if needed.
  5. Use [property: Page.mouse] to click in the center of the element.
  6. Ensure that the element is now checked. If not, this method throws.

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

Parameters:

  • selector (String)
  • force: (Boolean) (defaults to: nil)
  • noWaitAfter: (Boolean) (defaults to: nil)
  • position: (Hash[untyped, untyped]) (defaults to: nil)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)
  • trial: (Boolean) (defaults to: nil)


152
153
154
155
156
157
158
159
160
161
# File 'lib/playwright_api/page.rb', line 152

def check(
      selector,
      force: nil,
      noWaitAfter: nil,
      position: nil,
      strict: nil,
      timeout: nil,
      trial: nil)
  wrap_impl(@impl.check(unwrap_impl(selector), force: unwrap_impl(force), noWaitAfter: unwrap_impl(noWaitAfter), position: unwrap_impl(position), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout), trial: unwrap_impl(trial)))
end

#checked?(selector, strict: nil, timeout: nil) ⇒ Boolean

Returns whether the element is checked. Throws if the element is not a checkbox or radio input.

Parameters:

  • selector (String)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Returns:

  • (Boolean)


916
917
918
# File 'lib/playwright_api/page.rb', line 916

def checked?(selector, strict: nil, timeout: nil)
  wrap_impl(@impl.checked?(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout)))
end

#clear_console_messagesvoid

This method returns an undefined value.

Clears all stored console messages from this page. Subsequent calls to [method: Page.consoleMessages] will only return messages logged after the clear.



958
959
960
# File 'lib/playwright_api/page.rb', line 958

def clear_console_messages
  wrap_impl(@impl.clear_console_messages)
end

#clear_page_errorsvoid

This method returns an undefined value.

Clears all stored page errors from this page. Subsequent calls to [method: Page.pageErrors] will only return errors thrown after the clear.



964
965
966
# File 'lib/playwright_api/page.rb', line 964

def clear_page_errors
  wrap_impl(@impl.clear_page_errors)
end

#click(selector, button: nil, clickCount: nil, delay: nil, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) ⇒ void

This method returns an undefined value.

This method clicks an element matching selector by performing the following steps:

  1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
  2. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
  3. Scroll the element into view if needed.
  4. Use [property: Page.mouse] to click in the center of the element, or the specified position.
  5. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

Parameters:

  • selector (String)
  • button: ("left", "right", "middle") (defaults to: nil)
  • clickCount: (Integer) (defaults to: nil)
  • delay: (Float) (defaults to: nil)
  • force: (Boolean) (defaults to: nil)
  • modifiers: (Array[untyped]) (defaults to: nil)
  • noWaitAfter: (Boolean) (defaults to: nil)
  • position: (Hash[untyped, untyped]) (defaults to: nil)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)
  • trial: (Boolean) (defaults to: nil)


173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/playwright_api/page.rb', line 173

def click(
      selector,
      button: nil,
      clickCount: nil,
      delay: nil,
      force: nil,
      modifiers: nil,
      noWaitAfter: nil,
      position: nil,
      strict: nil,
      timeout: nil,
      trial: nil)
  wrap_impl(@impl.click(unwrap_impl(selector), button: unwrap_impl(button), clickCount: unwrap_impl(clickCount), delay: unwrap_impl(delay), force: unwrap_impl(force), modifiers: unwrap_impl(modifiers), noWaitAfter: unwrap_impl(noWaitAfter), position: unwrap_impl(position), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout), trial: unwrap_impl(trial)))
end

#close(reason: nil, runBeforeUnload: nil) ⇒ void

This method returns an undefined value.

If runBeforeUnload is false, does not run any unload handlers and waits for the page to be closed. If runBeforeUnload is true the method will run unload handlers, but will not wait for the page to close.

By default, page.close() does not run beforeunload handlers.

NOTE: if runBeforeUnload is passed as true, a beforeunload dialog might be summoned and should be handled manually via [event: Page.dialog] event.

Parameters:

  • reason: (String) (defaults to: nil)
  • runBeforeUnload: (Boolean) (defaults to: nil)


196
197
198
# File 'lib/playwright_api/page.rb', line 196

def close(reason: nil, runBeforeUnload: nil)
  wrap_impl(@impl.close(reason: unwrap_impl(reason), runBeforeUnload: unwrap_impl(runBeforeUnload)))
end

#closed?Boolean

Indicates that the page has been closed.

Returns:

  • (Boolean)


922
923
924
# File 'lib/playwright_api/page.rb', line 922

def closed?
  wrap_impl(@impl.closed?)
end

#console_messages(filter: nil) ⇒ Array[untyped]

Returns up to (currently) 200 last console messages from this page. See [event: Page.console] for more details.

Parameters:

  • filter: ("all", "since-navigation") (defaults to: nil)

Returns:

  • (Array[untyped])


970
971
972
# File 'lib/playwright_api/page.rb', line 970

def console_messages(filter: nil)
  wrap_impl(@impl.console_messages(filter: unwrap_impl(filter)))
end

#contentString

Gets the full HTML contents of the page, including the doctype.

Returns:

  • (String)


202
203
204
# File 'lib/playwright_api/page.rb', line 202

def content
  wrap_impl(@impl.content)
end

#contextBrowserContext

Get the browser context that the page belongs to.

Returns:



208
209
210
# File 'lib/playwright_api/page.rb', line 208

def context
  wrap_impl(@impl.context)
end

#dblclick(selector, button: nil, delay: nil, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) ⇒ void

This method returns an undefined value.

This method double clicks an element matching selector by performing the following steps:

  1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
  2. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
  3. Scroll the element into view if needed.
  4. Use [property: Page.mouse] to double click in the center of the element, or the specified position.

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

NOTE: page.dblclick() dispatches two click events and a single dblclick event.

Parameters:

  • selector (String)
  • button: ("left", "right", "middle") (defaults to: nil)
  • delay: (Float) (defaults to: nil)
  • force: (Boolean) (defaults to: nil)
  • modifiers: (Array[untyped]) (defaults to: nil)
  • noWaitAfter: (Boolean) (defaults to: nil)
  • position: (Hash[untyped, untyped]) (defaults to: nil)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)
  • trial: (Boolean) (defaults to: nil)


223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/playwright_api/page.rb', line 223

def dblclick(
      selector,
      button: nil,
      delay: nil,
      force: nil,
      modifiers: nil,
      noWaitAfter: nil,
      position: nil,
      strict: nil,
      timeout: nil,
      trial: nil)
  wrap_impl(@impl.dblclick(unwrap_impl(selector), button: unwrap_impl(button), delay: unwrap_impl(delay), force: unwrap_impl(force), modifiers: unwrap_impl(modifiers), noWaitAfter: unwrap_impl(noWaitAfter), position: unwrap_impl(position), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout), trial: unwrap_impl(trial)))
end

#disabled?(selector, strict: nil, timeout: nil) ⇒ Boolean

Returns whether the element is disabled, the opposite of enabled.

Parameters:

  • selector (String)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Returns:

  • (Boolean)


928
929
930
# File 'lib/playwright_api/page.rb', line 928

def disabled?(selector, strict: nil, timeout: nil)
  wrap_impl(@impl.disabled?(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout)))
end

#dispatch_event(selector, type, eventInit: nil, strict: nil, timeout: nil) ⇒ void

This method returns an undefined value.

The snippet below dispatches the click event on the element. Regardless of the visibility state of the element, click is dispatched. This is equivalent to calling element.click().

Usage

page.dispatch_event("button#submit", "click")

Under the hood, it creates an instance of an event based on the given type, initializes it with eventInit properties and dispatches it on the element. Events are composed, cancelable and bubble by default.

Since eventInit is event-specific, please refer to the events documentation for the lists of initial properties:

You can also specify JSHandle as the property value if you want live objects to be passed into the event:

# note you can only create data_transfer in chromium and firefox
data_transfer = page.evaluate_handle("new DataTransfer()")
page.dispatch_event("#source", "dragstart", { "dataTransfer": data_transfer })

Parameters:

  • selector (String)
  • type_ (String)
  • eventInit: (Object) (defaults to: nil)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)


272
273
274
275
276
277
278
279
# File 'lib/playwright_api/page.rb', line 272

def dispatch_event(
      selector,
      type,
      eventInit: nil,
      strict: nil,
      timeout: nil)
  wrap_impl(@impl.dispatch_event(unwrap_impl(selector), unwrap_impl(type), eventInit: unwrap_impl(eventInit), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout)))
end

#drag_and_drop(source, target, force: nil, noWaitAfter: nil, sourcePosition: nil, steps: nil, strict: nil, targetPosition: nil, timeout: nil, trial: nil) ⇒ void

This method returns an undefined value.

This method drags the source element to the target element. It will first move to the source element, perform a mousedown, then move to the target element and perform a mouseup.

Usage

page.drag_and_drop("#source", "#target")
# or specify exact positions relative to the top-left corners of the elements:
page.drag_and_drop(
  "#source",
  "#target",
  source_position={"x": 34, "y": 7},
  target_position={"x": 10, "y": 20}
)

Parameters:

  • source (String)
  • target (String)
  • force: (Boolean) (defaults to: nil)
  • noWaitAfter: (Boolean) (defaults to: nil)
  • sourcePosition: (Hash[untyped, untyped]) (defaults to: nil)
  • steps: (Integer) (defaults to: nil)
  • strict: (Boolean) (defaults to: nil)
  • targetPosition: (Hash[untyped, untyped]) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)
  • trial: (Boolean) (defaults to: nil)


298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/playwright_api/page.rb', line 298

def drag_and_drop(
      source,
      target,
      force: nil,
      noWaitAfter: nil,
      sourcePosition: nil,
      steps: nil,
      strict: nil,
      targetPosition: nil,
      timeout: nil,
      trial: nil)
  wrap_impl(@impl.drag_and_drop(unwrap_impl(source), unwrap_impl(target), force: unwrap_impl(force), noWaitAfter: unwrap_impl(noWaitAfter), sourcePosition: unwrap_impl(sourcePosition), steps: unwrap_impl(steps), strict: unwrap_impl(strict), targetPosition: unwrap_impl(targetPosition), timeout: unwrap_impl(timeout), trial: unwrap_impl(trial)))
end

#editable?(selector, strict: nil, timeout: nil) ⇒ Boolean

Returns whether the element is editable.

Parameters:

  • selector (String)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Returns:

  • (Boolean)


934
935
936
# File 'lib/playwright_api/page.rb', line 934

def editable?(selector, strict: nil, timeout: nil)
  wrap_impl(@impl.editable?(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout)))
end

#emulate_media(colorScheme: nil, contrast: nil, forcedColors: nil, media: nil, reducedMotion: nil) ⇒ void

This method returns an undefined value.

This method changes the CSS media type through the media argument, and/or the 'prefers-colors-scheme' media feature, using the colorScheme argument.

Usage

page.evaluate("matchMedia('screen').matches")
# → True
page.evaluate("matchMedia('print').matches")
# → False

page.emulate_media(media="print")
page.evaluate("matchMedia('screen').matches")
# → False
page.evaluate("matchMedia('print').matches")
# → True

page.emulate_media()
page.evaluate("matchMedia('screen').matches")
# → True
page.evaluate("matchMedia('print').matches")
# → False
page.emulate_media(color_scheme="dark")
page.evaluate("matchMedia('(prefers-color-scheme: dark)').matches")
# → True
page.evaluate("matchMedia('(prefers-color-scheme: light)').matches")
# → False

Parameters:

  • colorScheme: ("light", "dark", "no-preference", "null") (defaults to: nil)
  • contrast: ("no-preference", "more", "null") (defaults to: nil)
  • forcedColors: ("active", "none", "null") (defaults to: nil)
  • media: ("screen", "print", "null") (defaults to: nil)
  • reducedMotion: ("reduce", "no-preference", "null") (defaults to: nil)


343
344
345
346
347
348
349
350
# File 'lib/playwright_api/page.rb', line 343

def emulate_media(
      colorScheme: nil,
      contrast: nil,
      forcedColors: nil,
      media: nil,
      reducedMotion: nil)
  wrap_impl(@impl.emulate_media(colorScheme: unwrap_impl(colorScheme), contrast: unwrap_impl(contrast), forcedColors: unwrap_impl(forcedColors), media: unwrap_impl(media), reducedMotion: unwrap_impl(reducedMotion)))
end

#enabled?(selector, strict: nil, timeout: nil) ⇒ Boolean

Returns whether the element is enabled.

Parameters:

  • selector (String)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Returns:

  • (Boolean)


940
941
942
# File 'lib/playwright_api/page.rb', line 940

def enabled?(selector, strict: nil, timeout: nil)
  wrap_impl(@impl.enabled?(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout)))
end

#eval_on_selector(selector, expression, arg: nil, strict: nil) ⇒ Object

The method finds an element matching the specified selector within the page and passes it as a first argument to expression. If no elements match the selector, the method throws an error. Returns the value of expression.

If expression returns a [Promise], then [method: Page.evalOnSelector] would wait for the promise to resolve and return its value.

Usage

search_value = page.eval_on_selector("#search", "el => el.value")
preload_href = page.eval_on_selector("link[rel=preload]", "el => el.href")
html = page.eval_on_selector(".main-container", "(e, suffix) => e.outer_html + suffix", "hello")

Parameters:

  • selector (String)
  • expression (String)
  • arg: (Object) (defaults to: nil)
  • strict: (Boolean) (defaults to: nil)

Returns:

  • (Object)


367
368
369
# File 'lib/playwright_api/page.rb', line 367

def eval_on_selector(selector, expression, arg: nil, strict: nil)
  wrap_impl(@impl.eval_on_selector(unwrap_impl(selector), unwrap_impl(expression), arg: unwrap_impl(arg), strict: unwrap_impl(strict)))
end

#eval_on_selector_all(selector, expression, arg: nil) ⇒ Object

The method finds all elements matching the specified selector within the page and passes an array of matched elements as a first argument to expression. Returns the result of expression invocation.

If expression returns a [Promise], then [method: Page.evalOnSelectorAll] would wait for the promise to resolve and return its value.

Usage

div_counts = page.eval_on_selector_all("div", "(divs, min) => divs.length >= min", 10)

Parameters:

  • selector (String)
  • expression (String)
  • arg: (Object) (defaults to: nil)

Returns:

  • (Object)


383
384
385
# File 'lib/playwright_api/page.rb', line 383

def eval_on_selector_all(selector, expression, arg: nil)
  wrap_impl(@impl.eval_on_selector_all(unwrap_impl(selector), unwrap_impl(expression), arg: unwrap_impl(arg)))
end

#evaluate(expression, arg: nil) ⇒ Object

Returns the value of the expression invocation.

If the function passed to the [method: Page.evaluate] returns a [Promise], then [method: Page.evaluate] would wait for the promise to resolve and return its value.

If the function passed to the [method: Page.evaluate] returns a non-[Serializable] value, then [method: Page.evaluate] resolves to undefined. Playwright also supports transferring some additional values that are not serializable by JSON: -0, NaN, Infinity, -Infinity.

Usage

Passing argument to expression:

result = page.evaluate("([x, y]) => Promise.resolve(x * y)", [7, 8])
print(result) # prints "56"

A string can also be passed in instead of a function:

print(page.evaluate("1 + 2")) # prints "3"
x = 10
print(page.evaluate(f"1 + {x}")) # prints "11"

ElementHandle instances can be passed as an argument to the [method: Page.evaluate]:

body_handle = page.evaluate_handle("document.body")
html = page.evaluate("([body, suffix]) => body.innerHTML + suffix", [body_handle, "hello"])
body_handle.dispose()

Parameters:

  • expression (String)
  • arg: (Object) (defaults to: nil)

Returns:

  • (Object)


421
422
423
# File 'lib/playwright_api/page.rb', line 421

def evaluate(expression, arg: nil)
  wrap_impl(@impl.evaluate(unwrap_impl(expression), arg: unwrap_impl(arg)))
end

#evaluate_handle(expression, arg: nil) ⇒ JSHandle

Returns the value of the expression invocation as a JSHandle.

The only difference between [method: Page.evaluate] and [method: Page.evaluateHandle] is that [method: Page.evaluateHandle] returns JSHandle.

If the function passed to the [method: Page.evaluateHandle] returns a [Promise], then [method: Page.evaluateHandle] would wait for the promise to resolve and return its value.

Usage

a_window_handle = page.evaluate_handle("Promise.resolve(window)")
a_window_handle # handle for the window object.

A string can also be passed in instead of a function:

a_handle = page.evaluate_handle("document") # handle for the "document"

JSHandle instances can be passed as an argument to the [method: Page.evaluateHandle]:

a_handle = page.evaluate_handle("document.body")
result_handle = page.evaluate_handle("body => body.innerHTML", a_handle)
print(result_handle.json_value())
result_handle.dispose()

Parameters:

  • expression (String)
  • arg: (Object) (defaults to: nil)

Returns:



454
455
456
# File 'lib/playwright_api/page.rb', line 454

def evaluate_handle(expression, arg: nil)
  wrap_impl(@impl.evaluate_handle(unwrap_impl(expression), arg: unwrap_impl(arg)))
end

#expect_console_message(predicate: nil, timeout: nil) { ... } ⇒ ConsoleMessage

Performs action and waits for a ConsoleMessage to be logged by in the page. If predicate is provided, it passes ConsoleMessage value into the predicate function and waits for predicate(message) to return a truthy value. Will throw an error if the page is closed before the [event: Page.console] event is fired.

Parameters:

  • predicate: (function) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Yields:

Yield Returns:

  • (void)

Returns:



1607
1608
1609
# File 'lib/playwright_api/page.rb', line 1607

def expect_console_message(predicate: nil, timeout: nil, &block)
  wrap_impl(@impl.expect_console_message(predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block)))
end

#expect_download(predicate: nil, timeout: nil) { ... } ⇒ Download

Performs action and waits for a new Download. If predicate is provided, it passes Download value into the predicate function and waits for predicate(download) to return a truthy value. Will throw an error if the page is closed before the download event is fired.

Parameters:

  • predicate: (function) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Yields:

Yield Returns:

  • (void)

Returns:



1615
1616
1617
# File 'lib/playwright_api/page.rb', line 1615

def expect_download(predicate: nil, timeout: nil, &block)
  wrap_impl(@impl.expect_download(predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block)))
end

#expect_event(event, predicate: nil, timeout: nil) { ... } ⇒ Object

Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy value. Will throw an error if the page is closed before the event is fired. Returns the event data value.

Usage

with page.expect_event("framenavigated") as event_info:
    page.get_by_role("button")
frame = event_info.value

Parameters:

  • event (String)
  • predicate: (function) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Yields:

Yield Returns:

  • (void)

Returns:

  • (Object)


1630
1631
1632
# File 'lib/playwright_api/page.rb', line 1630

def expect_event(event, predicate: nil, timeout: nil, &block)
  wrap_impl(@impl.expect_event(unwrap_impl(event), predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block)))
end

#expect_file_chooser(predicate: nil, timeout: nil) { ... } ⇒ FileChooser

Performs action and waits for a new FileChooser to be created. If predicate is provided, it passes FileChooser value into the predicate function and waits for predicate(fileChooser) to return a truthy value. Will throw an error if the page is closed before the file chooser is opened.

Parameters:

  • predicate: (function) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Yields:

Yield Returns:

  • (void)

Returns:



1638
1639
1640
# File 'lib/playwright_api/page.rb', line 1638

def expect_file_chooser(predicate: nil, timeout: nil, &block)
  wrap_impl(@impl.expect_file_chooser(predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block)))
end

#expect_navigation(timeout: nil, url: nil, waitUntil: nil) { ... } ⇒ nil, Response

Deprecated.

This method is inherently racy, please use [method: Page.waitForURL] instead.

Waits for the main frame navigation and returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with null.

Usage

This resolves when the page navigates to a new URL or reloads. It is useful for when you run code which will indirectly cause the page to navigate. e.g. The click target has an onclick handler that triggers navigation from a setTimeout. Consider this example:

with page.expect_navigation():
    # This action triggers the navigation after a timeout.
    page.get_by_text("Navigate after timeout").click()
# Resolves after navigation has finished

NOTE: Usage of the History API to change the URL is considered a navigation.

Parameters:

  • timeout: (Float) (defaults to: nil)
  • url: (String, Regexp, function) (defaults to: nil)
  • waitUntil: ("load", "domcontentloaded", "networkidle", "commit") (defaults to: nil)

Yields:

Yield Returns:

  • (void)

Returns:



1723
1724
1725
# File 'lib/playwright_api/page.rb', line 1723

def expect_navigation(timeout: nil, url: nil, waitUntil: nil, &block)
  wrap_impl(@impl.expect_navigation(timeout: unwrap_impl(timeout), url: unwrap_impl(url), waitUntil: unwrap_impl(waitUntil), &wrap_block_call(block)))
end

#expect_popup(predicate: nil, timeout: nil) { ... } ⇒ Page

Performs action and waits for a popup Page. If predicate is provided, it passes [Popup] value into the predicate function and waits for predicate(page) to return a truthy value. Will throw an error if the page is closed before the popup event is fired.

Parameters:

  • predicate: (function) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Yields:

Yield Returns:

  • (void)

Returns:



1731
1732
1733
# File 'lib/playwright_api/page.rb', line 1731

def expect_popup(predicate: nil, timeout: nil, &block)
  wrap_impl(@impl.expect_popup(predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block)))
end

#expect_request(urlOrPredicate, timeout: nil) { ... } ⇒ Request

Waits for the matching request and returns it. See waiting for event for more details about events.

Usage

with page.expect_request("http://example.com/resource") as first:
    page.get_by_text("trigger request").click()
first_request = first.value

# or with a lambda
with page.expect_request(lambda request: request.url == "http://example.com" and request.method == "get") as second:
    page.get_by_text("trigger request").click()
second_request = second.value

Parameters:

  • urlOrPredicate (String, Regexp, function)
  • timeout: (Float) (defaults to: nil)

Yields:

Yield Returns:

  • (void)

Returns:



1750
1751
1752
# File 'lib/playwright_api/page.rb', line 1750

def expect_request(urlOrPredicate, timeout: nil, &block)
  wrap_impl(@impl.expect_request(unwrap_impl(urlOrPredicate), timeout: unwrap_impl(timeout), &wrap_block_call(block)))
end

#expect_request_finished(predicate: nil, timeout: nil) { ... } ⇒ Request

Performs action and waits for a Request to finish loading. If predicate is provided, it passes Request value into the predicate function and waits for predicate(request) to return a truthy value. Will throw an error if the page is closed before the [event: Page.requestFinished] event is fired.

Parameters:

  • predicate: (function) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Yields:

Yield Returns:

  • (void)

Returns:



1758
1759
1760
# File 'lib/playwright_api/page.rb', line 1758

def expect_request_finished(predicate: nil, timeout: nil, &block)
  wrap_impl(@impl.expect_request_finished(predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block)))
end

#expect_response(urlOrPredicate, timeout: nil) { ... } ⇒ Response

Returns the matched response. See waiting for event for more details about events.

Usage

with page.expect_response("https://example.com/resource") as response_info:
    page.get_by_text("trigger response").click()
response = response_info.value
return response.ok

# or with a lambda
with page.expect_response(lambda response: response.url == "https://example.com" and response.status == 200 and response.request.method == "get") as response_info:
    page.get_by_text("trigger response").click()
response = response_info.value
return response.ok

Parameters:

  • urlOrPredicate (String, Regexp, function)
  • timeout: (Float) (defaults to: nil)

Yields:

Yield Returns:

  • (void)

Returns:



1779
1780
1781
# File 'lib/playwright_api/page.rb', line 1779

def expect_response(urlOrPredicate, timeout: nil, &block)
  wrap_impl(@impl.expect_response(unwrap_impl(urlOrPredicate), timeout: unwrap_impl(timeout), &wrap_block_call(block)))
end

#expect_websocket(predicate: nil, timeout: nil) { ... } ⇒ WebSocket

Performs action and waits for a new WebSocket. If predicate is provided, it passes WebSocket value into the predicate function and waits for predicate(webSocket) to return a truthy value. Will throw an error if the page is closed before the WebSocket event is fired.

Parameters:

  • predicate: (function) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Yields:

Yield Returns:

  • (void)

Returns:



1852
1853
1854
# File 'lib/playwright_api/page.rb', line 1852

def expect_websocket(predicate: nil, timeout: nil, &block)
  wrap_impl(@impl.expect_websocket(predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block)))
end

#expect_worker(predicate: nil, timeout: nil) { ... } ⇒ Worker

Performs action and waits for a new Worker. If predicate is provided, it passes Worker value into the predicate function and waits for predicate(worker) to return a truthy value. Will throw an error if the page is closed before the worker event is fired.

Parameters:

  • predicate: (function) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Yields:

Yield Returns:

  • (void)

Returns:



1860
1861
1862
# File 'lib/playwright_api/page.rb', line 1860

def expect_worker(predicate: nil, timeout: nil, &block)
  wrap_impl(@impl.expect_worker(predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block)))
end

#expose_binding(name, callback) ⇒ Object

The method adds a function called name on the window object of every frame in this page. When called, the function executes callback and returns a [Promise] which resolves to the return value of callback. If the callback returns a [Promise], it will be awaited.

The first argument of the callback function contains information about the caller: { browserContext: BrowserContext, page: Page, frame: Frame }.

See [method: BrowserContext.exposeBinding] for the context-wide version.

NOTE: Functions installed via [method: Page.exposeBinding] survive navigations.

Usage

An example of exposing page URL to all frames in a page:

from playwright.sync_api import sync_playwright, Playwright

def run(playwright: Playwright):
    webkit = playwright.webkit
    browser = webkit.launch(headless=False)
    context = browser.new_context()
    page = context.new_page()
    page.expose_binding("pageURL", lambda source: source["page"].url)
    page.set_content("""
    <script>
      async function onClick() {
        document.querySelector('div').textContent = await window.pageURL();
      }
    </script>
    <button onclick="onClick()">Click me</button>
    <div></div>
    """)
    page.click("button")

with sync_playwright() as playwright:
    run(playwright)

Parameters:

  • name (String)
  • callback (function)

Returns:

  • (Object)


497
498
499
# File 'lib/playwright_api/page.rb', line 497

def expose_binding(name, callback)
  wrap_impl(@impl.expose_binding(unwrap_impl(name), unwrap_impl(callback)))
end

#expose_function(name, callback) ⇒ Object

The method adds a function called name on the window object of every frame in the page. When called, the function executes callback and returns a [Promise] which resolves to the return value of callback.

If the callback returns a [Promise], it will be awaited.

See [method: BrowserContext.exposeFunction] for context-wide exposed function.

NOTE: Functions installed via [method: Page.exposeFunction] survive navigations.

Usage

An example of adding a sha256 function to the page:

import hashlib
from playwright.sync_api import sync_playwright, Playwright

def sha256(text):
    m = hashlib.sha256()
    m.update(bytes(text, "utf8"))
    return m.hexdigest()


def run(playwright: Playwright):
    webkit = playwright.webkit
    browser = webkit.launch(headless=False)
    page = browser.new_page()
    page.expose_function("sha256", sha256)
    page.set_content("""
        <script>
          async function onClick() {
            document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');
          }
        </script>
        <button onclick="onClick()">Click me</button>
        <div></div>
    """)
    page.click("button")

with sync_playwright() as playwright:
    run(playwright)

Parameters:

  • name (String)
  • callback (function)

Returns:

  • (Object)


544
545
546
# File 'lib/playwright_api/page.rb', line 544

def expose_function(name, callback)
  wrap_impl(@impl.expose_function(unwrap_impl(name), unwrap_impl(callback)))
end

#fill(selector, value, force: nil, noWaitAfter: nil, strict: nil, timeout: nil) ⇒ void

This method returns an undefined value.

This method waits for an element matching selector, waits for actionability checks, focuses the element, fills it and triggers an input event after filling. Note that you can pass an empty string to clear the input field.

If the target element is not an <input>, <textarea> or [contenteditable] element, this method throws an error. However, if the element is inside the <label> element that has an associated control, the control will be filled instead.

To send fine-grained keyboard events, use [method: Locator.pressSequentially].

Parameters:

  • selector (String)
  • value (String)
  • force: (Boolean) (defaults to: nil)
  • noWaitAfter: (Boolean) (defaults to: nil)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)


554
555
556
557
558
559
560
561
562
# File 'lib/playwright_api/page.rb', line 554

def fill(
      selector,
      value,
      force: nil,
      noWaitAfter: nil,
      strict: nil,
      timeout: nil)
  wrap_impl(@impl.fill(unwrap_impl(selector), unwrap_impl(value), force: unwrap_impl(force), noWaitAfter: unwrap_impl(noWaitAfter), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout)))
end

#focus(selector, strict: nil, timeout: nil) ⇒ void

This method returns an undefined value.

This method fetches an element with selector and focuses it. If there's no element matching selector, the method waits until a matching element appears in the DOM.

Parameters:

  • selector (String)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)


567
568
569
# File 'lib/playwright_api/page.rb', line 567

def focus(selector, strict: nil, timeout: nil)
  wrap_impl(@impl.focus(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout)))
end

#frame(name: nil, url: nil) ⇒ nil, Frame

Returns frame matching the specified criteria. Either name or url must be specified.

Usage

frame = page.frame(name="frame-name")
frame = page.frame(url=r".*domain.*")

Parameters:

  • name: (String) (defaults to: nil)
  • url: (String, Regexp, function) (defaults to: nil)

Returns:



583
584
585
# File 'lib/playwright_api/page.rb', line 583

def frame(name: nil, url: nil)
  wrap_impl(@impl.frame(name: unwrap_impl(name), url: unwrap_impl(url)))
end

#frame_locator(selector) ⇒ FrameLocator

When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements in that iframe.

Usage

Following snippet locates element with text "Submit" in the iframe with id my-frame, like <iframe id="my-frame">:

locator = page.frame_locator("#my-iframe").get_by_text("Submit")
locator.click()

Parameters:

  • selector (String)

Returns:



600
601
602
# File 'lib/playwright_api/page.rb', line 600

def frame_locator(selector)
  wrap_impl(@impl.frame_locator(unwrap_impl(selector)))
end

#framesArray[untyped]

An array of all frames attached to the page.

Returns:

  • (Array[untyped])


606
607
608
# File 'lib/playwright_api/page.rb', line 606

def frames
  wrap_impl(@impl.frames)
end

#get_attribute(selector, name, strict: nil, timeout: nil) ⇒ nil, String

Returns element attribute value.

Parameters:

  • selector (String)
  • name (String)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Returns:

  • (nil, String)


612
613
614
# File 'lib/playwright_api/page.rb', line 612

def get_attribute(selector, name, strict: nil, timeout: nil)
  wrap_impl(@impl.get_attribute(unwrap_impl(selector), unwrap_impl(name), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout)))
end

#get_by_alt_text(text, exact: nil) ⇒ Locator

Allows locating elements by their alt text.

Usage

For example, this method will find the image by alt text "Playwright logo":

<img alt='Playwright logo'>
page.get_by_alt_text("Playwright logo").click()

Parameters:

  • text (String, Regexp)
  • exact: (Boolean) (defaults to: nil)

Returns:



630
631
632
# File 'lib/playwright_api/page.rb', line 630

def get_by_alt_text(text, exact: nil)
  wrap_impl(@impl.get_by_alt_text(unwrap_impl(text), exact: unwrap_impl(exact)))
end

#get_by_label(text, exact: nil) ⇒ Locator

Allows locating input elements by the text of the associated <label> or aria-labelledby element, or by the aria-label attribute.

Usage

For example, this method will find inputs by label "Username" and "Password" in the following DOM:

<input aria-label="Username">
<label for="password-input">Password:</label>
<input id="password-input">
page.get_by_label("Username").fill("john")
page.get_by_label("Password").fill("secret")

Parameters:

  • text (String, Regexp)
  • exact: (Boolean) (defaults to: nil)

Returns:



651
652
653
# File 'lib/playwright_api/page.rb', line 651

def get_by_label(text, exact: nil)
  wrap_impl(@impl.get_by_label(unwrap_impl(text), exact: unwrap_impl(exact)))
end

#get_by_placeholder(text, exact: nil) ⇒ Locator

Allows locating input elements by the placeholder text.

Usage

For example, consider the following DOM structure.

<input type="email" placeholder="name@example.com" />

You can fill the input after locating it by the placeholder text:

page.get_by_placeholder("name@example.com").fill("playwright@microsoft.com")

Parameters:

  • text (String, Regexp)
  • exact: (Boolean) (defaults to: nil)

Returns:



671
672
673
# File 'lib/playwright_api/page.rb', line 671

def get_by_placeholder(text, exact: nil)
  wrap_impl(@impl.get_by_placeholder(unwrap_impl(text), exact: unwrap_impl(exact)))
end

#get_by_role(role, checked: nil, description: nil, disabled: nil, exact: nil, expanded: nil, includeHidden: nil, level: nil, name: nil, pressed: nil, selected: nil) ⇒ Locator

Allows locating elements by their ARIA role, ARIA attributes and accessible name.

Usage

Consider the following DOM structure.

<h3>Sign up</h3>
<label>
  <input type="checkbox" /> Subscribe
</label>
<br/>
<button>Submit</button>

You can locate each element by its implicit role:

expect(page.get_by_role("heading", name="Sign up")).to_be_visible()

page.get_by_role("checkbox", name="Subscribe").check()

page.get_by_role("button", name=re.compile("submit", re.IGNORECASE)).click()

Details

Role selector does not replace accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.

Many html elements have an implicitly defined role that is recognized by the role selector. You can find all the supported roles here. ARIA guidelines do not recommend duplicating implicit roles and attributes by setting role and/or aria-* attributes to default values.

Parameters:

  • role ("alert", "alertdialog", "application", "article", "banner", "blockquote", "button", "caption", "cell", "checkbox", "code", "columnheader", "combobox", "complementary", "contentinfo", "definition", "deletion", "dialog", "directory", "document", "emphasis", "feed", "figure", "form", "generic", "grid", "gridcell", "group", "heading", "img", "insertion", "link", "list", "listbox", "listitem", "log", "main", "marquee", "math", "meter", "menu", "menubar", "menuitem", "menuitemcheckbox", "menuitemradio", "navigation", "none", "note", "option", "paragraph", "presentation", "progressbar", "radio", "radiogroup", "region", "row", "rowgroup", "rowheader", "scrollbar", "search", "searchbox", "separator", "slider", "spinbutton", "status", "strong", "subscript", "superscript", "switch", "tab", "table", "tablist", "tabpanel", "term", "textbox", "time", "timer", "toolbar", "tooltip", "tree", "treegrid", "treeitem")
  • checked: (Boolean) (defaults to: nil)
  • description: (String, Regexp) (defaults to: nil)
  • disabled: (Boolean) (defaults to: nil)
  • exact: (Boolean) (defaults to: nil)
  • expanded: (Boolean) (defaults to: nil)
  • includeHidden: (Boolean) (defaults to: nil)
  • level: (Integer) (defaults to: nil)
  • name: (String, Regexp) (defaults to: nil)
  • pressed: (Boolean) (defaults to: nil)
  • selected: (Boolean) (defaults to: nil)

Returns:



706
707
708
709
710
711
712
713
714
715
716
717
718
719
# File 'lib/playwright_api/page.rb', line 706

def get_by_role(
      role,
      checked: nil,
      description: nil,
      disabled: nil,
      exact: nil,
      expanded: nil,
      includeHidden: nil,
      level: nil,
      name: nil,
      pressed: nil,
      selected: nil)
  wrap_impl(@impl.get_by_role(unwrap_impl(role), checked: unwrap_impl(checked), description: unwrap_impl(description), disabled: unwrap_impl(disabled), exact: unwrap_impl(exact), expanded: unwrap_impl(expanded), includeHidden: unwrap_impl(includeHidden), level: unwrap_impl(level), name: unwrap_impl(name), pressed: unwrap_impl(pressed), selected: unwrap_impl(selected)))
end

#get_by_test_id(testId) ⇒ Locator Also known as: get_by_testid

Locate element by the test id.

Usage

Consider the following DOM structure.

<button data-testid="directions">Itinéraire</button>

You can locate the element by its test id:

page.get_by_test_id("directions").click()

Details

By default, the data-testid attribute is used as a test id. Use [method: Selectors.setTestIdAttribute] to configure a different test id attribute if necessary.

Parameters:

  • testId (String, Regexp)

Returns:



741
742
743
# File 'lib/playwright_api/page.rb', line 741

def get_by_test_id(testId)
  wrap_impl(@impl.get_by_test_id(unwrap_impl(testId)))
end

#get_by_text(text, exact: nil) ⇒ Locator

Allows locating elements that contain given text.

See also [method: Locator.filter] that allows to match by another criteria, like an accessible role, and then filter by the text content.

Usage

Consider the following DOM structure:

<div>Hello <span>world</span></div>
<div>Hello</div>

You can locate by text substring, exact string, or a regular expression:

# Matches <span>
page.get_by_text("world")

# Matches first <div>
page.get_by_text("Hello world")

# Matches second <div>
page.get_by_text("Hello", exact=True)

# Matches both <div>s
page.get_by_text(re.compile("Hello"))

# Matches second <div>
page.get_by_text(re.compile("^hello$", re.IGNORECASE))

Details

Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.

Input elements of the type button and submit are matched by their value instead of the text content. For example, locating by text "Log in" matches <input type=button value="Log in">.

Parameters:

  • text (String, Regexp)
  • exact: (Boolean) (defaults to: nil)

Returns:



784
785
786
# File 'lib/playwright_api/page.rb', line 784

def get_by_text(text, exact: nil)
  wrap_impl(@impl.get_by_text(unwrap_impl(text), exact: unwrap_impl(exact)))
end

#get_by_title(text, exact: nil) ⇒ Locator

Allows locating elements by their title attribute.

Usage

Consider the following DOM structure.

<span title='Issues count'>25 issues</span>

You can check the issues count after locating it by the title text:

expect(page.get_by_title("Issues count")).to_have_text("25 issues")

Parameters:

  • text (String, Regexp)
  • exact: (Boolean) (defaults to: nil)

Returns:



804
805
806
# File 'lib/playwright_api/page.rb', line 804

def get_by_title(text, exact: nil)
  wrap_impl(@impl.get_by_title(unwrap_impl(text), exact: unwrap_impl(exact)))
end

#go_back(timeout: nil, waitUntil: nil) ⇒ nil, Response

Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If cannot go back, returns null.

Navigate to the previous page in history.

Parameters:

  • timeout: (Float) (defaults to: nil)
  • waitUntil: ("load", "domcontentloaded", "networkidle", "commit") (defaults to: nil)

Returns:



813
814
815
# File 'lib/playwright_api/page.rb', line 813

def go_back(timeout: nil, waitUntil: nil)
  wrap_impl(@impl.go_back(timeout: unwrap_impl(timeout), waitUntil: unwrap_impl(waitUntil)))
end

#go_forward(timeout: nil, waitUntil: nil) ⇒ nil, Response

Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If cannot go forward, returns null.

Navigate to the next page in history.

Parameters:

  • timeout: (Float) (defaults to: nil)
  • waitUntil: ("load", "domcontentloaded", "networkidle", "commit") (defaults to: nil)

Returns:



822
823
824
# File 'lib/playwright_api/page.rb', line 822

def go_forward(timeout: nil, waitUntil: nil)
  wrap_impl(@impl.go_forward(timeout: unwrap_impl(timeout), waitUntil: unwrap_impl(waitUntil)))
end

#goto(url, referer: nil, timeout: nil, waitUntil: nil) ⇒ nil, Response

Returns the main resource response. In case of multiple redirects, the navigation will resolve with the first non-redirect response.

The method will throw an error if:

  • there's an SSL error (e.g. in case of self-signed certificates).
  • target URL is invalid.
  • the timeout is exceeded during navigation.
  • the remote server does not respond or is unreachable.
  • the main resource failed to load.

The method will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling [method: Response.status].

NOTE: The method either throws an error or returns a main resource response. The only exceptions are navigation to about:blank or navigation to the same URL with a different hash, which would succeed and return null.

NOTE: Headless mode doesn't support navigation to a PDF document. See the upstream issue.

Parameters:

  • url (String)
  • referer: (String) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)
  • waitUntil: ("load", "domcontentloaded", "networkidle", "commit") (defaults to: nil)

Returns:



863
864
865
# File 'lib/playwright_api/page.rb', line 863

def goto(url, referer: nil, timeout: nil, waitUntil: nil)
  wrap_impl(@impl.goto(unwrap_impl(url), referer: unwrap_impl(referer), timeout: unwrap_impl(timeout), waitUntil: unwrap_impl(waitUntil)))
end

#guidObject



1914
1915
1916
# File 'lib/playwright_api/page.rb', line 1914

def guid
  wrap_impl(@impl.guid)
end

#hidden?(selector, strict: nil, timeout: nil) ⇒ Boolean

Returns whether the element is hidden, the opposite of visible. selector that does not match any elements is considered hidden.

Parameters:

  • selector (String)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Returns:

  • (Boolean)


946
947
948
# File 'lib/playwright_api/page.rb', line 946

def hidden?(selector, strict: nil, timeout: nil)
  wrap_impl(@impl.hidden?(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout)))
end

#hide_highlightvoid

This method returns an undefined value.

Hide all locator highlight overlays previously added by [method: Locator.highlight] on this page.



869
870
871
# File 'lib/playwright_api/page.rb', line 869

def hide_highlight
  wrap_impl(@impl.hide_highlight)
end

#hover(selector, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) ⇒ void

This method returns an undefined value.

This method hovers over an element matching selector by performing the following steps:

  1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
  2. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
  3. Scroll the element into view if needed.
  4. Use [property: Page.mouse] to hover over the center of the element, or the specified position.

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

Parameters:

  • selector (String)
  • force: (Boolean) (defaults to: nil)
  • modifiers: (Array[untyped]) (defaults to: nil)
  • noWaitAfter: (Boolean) (defaults to: nil)
  • position: (Hash[untyped, untyped]) (defaults to: nil)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)
  • trial: (Boolean) (defaults to: nil)


882
883
884
885
886
887
888
889
890
891
892
# File 'lib/playwright_api/page.rb', line 882

def hover(
      selector,
      force: nil,
      modifiers: nil,
      noWaitAfter: nil,
      position: nil,
      strict: nil,
      timeout: nil,
      trial: nil)
  wrap_impl(@impl.hover(unwrap_impl(selector), force: unwrap_impl(force), modifiers: unwrap_impl(modifiers), noWaitAfter: unwrap_impl(noWaitAfter), position: unwrap_impl(position), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout), trial: unwrap_impl(trial)))
end

#inner_html(selector, strict: nil, timeout: nil) ⇒ String

Returns element.innerHTML.

Parameters:

  • selector (String)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Returns:

  • (String)


896
897
898
# File 'lib/playwright_api/page.rb', line 896

def inner_html(selector, strict: nil, timeout: nil)
  wrap_impl(@impl.inner_html(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout)))
end

#inner_text(selector, strict: nil, timeout: nil) ⇒ String

Returns element.innerText.

Parameters:

  • selector (String)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Returns:

  • (String)


902
903
904
# File 'lib/playwright_api/page.rb', line 902

def inner_text(selector, strict: nil, timeout: nil)
  wrap_impl(@impl.inner_text(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout)))
end

#input_value(selector, strict: nil, timeout: nil) ⇒ String

Returns input.value for the selected <input> or <textarea> or <select> element.

Throws for non-input elements. However, if the element is inside the <label> element that has an associated control, returns the value of the control.

Parameters:

  • selector (String)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Returns:

  • (String)


910
911
912
# File 'lib/playwright_api/page.rb', line 910

def input_value(selector, strict: nil, timeout: nil)
  wrap_impl(@impl.input_value(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout)))
end

#locator(selector, has: nil, hasNot: nil, hasNotText: nil, hasText: nil) ⇒ Locator

The method returns an element locator that can be used to perform actions on this page / frame. Locator is resolved to the element immediately before performing an action, so a series of actions on the same locator can in fact be performed on different DOM elements. That would happen if the DOM structure between those actions has changed.

Learn more about locators.

Parameters:

  • selector (String)
  • has: (Locator) (defaults to: nil)
  • hasNot: (Locator) (defaults to: nil)
  • hasNotText: (String, Regexp) (defaults to: nil)
  • hasText: (String, Regexp) (defaults to: nil)

Returns:



985
986
987
988
989
990
991
992
# File 'lib/playwright_api/page.rb', line 985

def locator(
      selector,
      has: nil,
      hasNot: nil,
      hasNotText: nil,
      hasText: nil)
  wrap_impl(@impl.locator(unwrap_impl(selector), has: unwrap_impl(has), hasNot: unwrap_impl(hasNot), hasNotText: unwrap_impl(hasNotText), hasText: unwrap_impl(hasText)))
end

#main_frameFrame

The page's main frame. Page is guaranteed to have a main frame which persists during navigations.

Returns:



996
997
998
# File 'lib/playwright_api/page.rb', line 996

def main_frame
  wrap_impl(@impl.main_frame)
end

#off(event, callback) ⇒ Object

-- inherited from EventEmitter --



1925
1926
1927
# File 'lib/playwright_api/page.rb', line 1925

def off(event, callback)
  event_emitter_proxy.off(event, callback)
end

#on(event, callback) ⇒ Object

-- inherited from EventEmitter --



1937
1938
1939
# File 'lib/playwright_api/page.rb', line 1937

def on(event, callback)
  event_emitter_proxy.on(event, callback)
end

#once(event, callback) ⇒ Object

-- inherited from EventEmitter --



1931
1932
1933
# File 'lib/playwright_api/page.rb', line 1931

def once(event, callback)
  event_emitter_proxy.once(event, callback)
end

#openernil, Page

Returns the opener for popup pages and null for others. If the opener has been closed already the returns null.

Returns:



1002
1003
1004
# File 'lib/playwright_api/page.rb', line 1002

def opener
  wrap_impl(@impl.opener)
end

#owned_context=(req) ⇒ Object



1919
1920
1921
# File 'lib/playwright_api/page.rb', line 1919

def owned_context=(req)
  wrap_impl(@impl.owned_context=(unwrap_impl(req)))
end

#page_errors(filter: nil) ⇒ Array[untyped]

Returns up to (currently) 200 last page errors from this page. See [event: Page.pageError] for more details.

Parameters:

  • filter: ("all", "since-navigation") (defaults to: nil)

Returns:

  • (Array[untyped])


976
977
978
# File 'lib/playwright_api/page.rb', line 976

def page_errors(filter: nil)
  wrap_impl(@impl.page_errors(filter: unwrap_impl(filter)))
end

#pausevoid

This method returns an undefined value.

Pauses script execution. Playwright will stop executing the script and wait for the user to either press the 'Resume' button in the page overlay or to call playwright.resume() in the DevTools console.

User can inspect selectors or perform manual steps while paused. Resume will continue running the original script from the place it was paused.

NOTE: This method requires Playwright to be started in a headed mode, with a falsy headless option.



1014
1015
1016
# File 'lib/playwright_api/page.rb', line 1014

def pause
  wrap_impl(@impl.pause)
end

#pdf(displayHeaderFooter: nil, footerTemplate: nil, format: nil, headerTemplate: nil, height: nil, landscape: nil, margin: nil, outline: nil, pageRanges: nil, path: nil, preferCSSPageSize: nil, printBackground: nil, scale: nil, tagged: nil, width: nil) ⇒ String

Returns the PDF buffer.

page.pdf() generates a pdf of the page with print css media. To generate a pdf with screen media, call [method: Page.emulateMedia] before calling page.pdf():

NOTE: By default, page.pdf() generates a pdf with modified colors for printing. Use the -webkit-print-color-adjust property to force rendering of exact colors.

Usage

# generates a pdf with "screen" media type.
page.emulate_media(media="screen")
page.pdf(path="page.pdf")

The width, height, and margin options accept values labeled with units. Unlabeled values are treated as pixels.

A few examples:

  • page.pdf({width: 100}) - prints with width set to 100 pixels
  • page.pdf({width: '100px'}) - prints with width set to 100 pixels
  • page.pdf({width: '10cm'}) - prints with width set to 10 centimeters.

All possible units are:

  • px - pixel
  • in - inch
  • cm - centimeter
  • mm - millimeter

The format options are:

  • Letter: 8.5in x 11in
  • Legal: 8.5in x 14in
  • Tabloid: 11in x 17in
  • Ledger: 17in x 11in
  • A0: 33.1in x 46.8in
  • A1: 23.4in x 33.1in
  • A2: 16.54in x 23.4in
  • A3: 11.7in x 16.54in
  • A4: 8.27in x 11.7in
  • A5: 5.83in x 8.27in
  • A6: 4.13in x 5.83in

NOTE: headerTemplate and footerTemplate markup have the following limitations: > 1. Script tags inside templates are not evaluated. > 2. Page styles are not visible inside templates.

Parameters:

  • displayHeaderFooter: (Boolean) (defaults to: nil)
  • footerTemplate: (String) (defaults to: nil)
  • format: (String) (defaults to: nil)
  • headerTemplate: (String) (defaults to: nil)
  • height: (String, Float) (defaults to: nil)
  • landscape: (Boolean) (defaults to: nil)
  • margin: (Hash[untyped, untyped]) (defaults to: nil)
  • outline: (Boolean) (defaults to: nil)
  • pageRanges: (String) (defaults to: nil)
  • path: (String, File) (defaults to: nil)
  • preferCSSPageSize: (Boolean) (defaults to: nil)
  • printBackground: (Boolean) (defaults to: nil)
  • scale: (Float) (defaults to: nil)
  • tagged: (Boolean) (defaults to: nil)
  • width: (String, Float) (defaults to: nil)

Returns:

  • (String)


1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
# File 'lib/playwright_api/page.rb', line 1065

def pdf(
      displayHeaderFooter: nil,
      footerTemplate: nil,
      format: nil,
      headerTemplate: nil,
      height: nil,
      landscape: nil,
      margin: nil,
      outline: nil,
      pageRanges: nil,
      path: nil,
      preferCSSPageSize: nil,
      printBackground: nil,
      scale: nil,
      tagged: nil,
      width: nil)
  wrap_impl(@impl.pdf(displayHeaderFooter: unwrap_impl(displayHeaderFooter), footerTemplate: unwrap_impl(footerTemplate), format: unwrap_impl(format), headerTemplate: unwrap_impl(headerTemplate), height: unwrap_impl(height), landscape: unwrap_impl(landscape), margin: unwrap_impl(margin), outline: unwrap_impl(outline), pageRanges: unwrap_impl(pageRanges), path: unwrap_impl(path), preferCSSPageSize: unwrap_impl(preferCSSPageSize), printBackground: unwrap_impl(printBackground), scale: unwrap_impl(scale), tagged: unwrap_impl(tagged), width: unwrap_impl(width)))
end

#pick_locatorLocator

Enters pick locator mode where hovering over page elements highlights them and shows the corresponding locator. Once the user clicks an element, the mode is deactivated and the Locator for the picked element is returned.

Usage

locator = page.pick_locator()
print(locator)

Returns:



1094
1095
1096
# File 'lib/playwright_api/page.rb', line 1094

def pick_locator
  wrap_impl(@impl.pick_locator)
end

#press(selector, key, delay: nil, noWaitAfter: nil, strict: nil, timeout: nil) ⇒ void

This method returns an undefined value.

Focuses the element, and then uses [method: Keyboard.down] and [method: Keyboard.up].

key can specify the intended keyboardEvent.key value or a single character to generate the text for. A superset of the key values can be found here. Examples of the keys are:

F1 - F12, Digit0- Digit9, KeyA- KeyZ, Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape, ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight, ArrowUp, etc.

Following modification shortcuts are also supported: Shift, Control, Alt, Meta, ShiftLeft, ControlOrMeta. ControlOrMeta resolves to Control on Windows and Linux and to Meta on macOS.

Holding down Shift will type the text that corresponds to the key in the upper case.

If key is a single character, it is case-sensitive, so the values a and A will generate different respective texts.

Shortcuts such as key: "Control+o", key: "Control++ or key: "Control+Shift+T" are supported as well. When specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.

Usage

page = browser.new_page()
page.goto("https://keycode.info")
page.press("body", "A")
page.screenshot(path="a.png")
page.press("body", "ArrowLeft")
page.screenshot(path="arrow_left.png")
page.press("body", "Shift+O")
page.screenshot(path="o.png")
browser.close()

Parameters:

  • selector (String)
  • key (String)
  • delay: (Float) (defaults to: nil)
  • noWaitAfter: (Boolean) (defaults to: nil)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)


1133
1134
1135
1136
1137
1138
1139
1140
1141
# File 'lib/playwright_api/page.rb', line 1133

def press(
      selector,
      key,
      delay: nil,
      noWaitAfter: nil,
      strict: nil,
      timeout: nil)
  wrap_impl(@impl.press(unwrap_impl(selector), unwrap_impl(key), delay: unwrap_impl(delay), noWaitAfter: unwrap_impl(noWaitAfter), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout)))
end

#query_selector(selector, strict: nil) ⇒ nil, ElementHandle

The method finds an element matching the specified selector within the page. If no elements match the selector, the return value resolves to null. To wait for an element on the page, use [method: Locator.waitFor].

Parameters:

  • selector (String)
  • strict: (Boolean) (defaults to: nil)

Returns:



1146
1147
1148
# File 'lib/playwright_api/page.rb', line 1146

def query_selector(selector, strict: nil)
  wrap_impl(@impl.query_selector(unwrap_impl(selector), strict: unwrap_impl(strict)))
end

#query_selector_all(selector) ⇒ Array[untyped]

The method finds all elements matching the specified selector within the page. If no elements match the selector, the return value resolves to [].

Parameters:

  • selector (String)

Returns:

  • (Array[untyped])


1153
1154
1155
# File 'lib/playwright_api/page.rb', line 1153

def query_selector_all(selector)
  wrap_impl(@impl.query_selector_all(unwrap_impl(selector)))
end

#reload(timeout: nil, waitUntil: nil) ⇒ nil, Response

This method reloads the current page, in the same way as if the user had triggered a browser refresh. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.

Parameters:

  • timeout: (Float) (defaults to: nil)
  • waitUntil: ("load", "domcontentloaded", "networkidle", "commit") (defaults to: nil)

Returns:



1247
1248
1249
# File 'lib/playwright_api/page.rb', line 1247

def reload(timeout: nil, waitUntil: nil)
  wrap_impl(@impl.reload(timeout: unwrap_impl(timeout), waitUntil: unwrap_impl(waitUntil)))
end

#remove_locator_handler(locator) ⇒ Object

Removes all locator handlers added by [method: Page.addLocatorHandler] for a specific locator.

Raises:

  • (NotImplementedError)


1239
1240
1241
# File 'lib/playwright_api/page.rb', line 1239

def remove_locator_handler(locator)
  raise NotImplementedError.new('remove_locator_handler is not implemented yet.')
end

#request_gcObject

Request the page to perform garbage collection. Note that there is no guarantee that all unreachable objects will be collected.

This is useful to help detect memory leaks. For example, if your page has a large object 'suspect' that might be leaked, you can check that it does not leak by using a WeakRef.

# 1. In your page, save a WeakRef for the "suspect".
page.evaluate("globalThis.suspectWeakRef = new WeakRef(suspect)")
# 2. Request garbage collection.
page.request_gc()
# 3. Check that weak ref does not deref to the original object.
assert page.evaluate("!globalThis.suspectWeakRef.deref()")

Raises:

  • (NotImplementedError)


839
840
841
# File 'lib/playwright_api/page.rb', line 839

def request_gc
  raise NotImplementedError.new('request_gc is not implemented yet.')
end

#requestsArray[untyped]

Returns up to (currently) 100 last network request from this page. See [event: Page.request] for more details.

Returned requests should be accessed immediately, otherwise they might be collected to prevent unbounded memory growth as new requests come in. Once collected, retrieving most information about the request is impossible.

Note that requests reported through the [event: Page.request] request are not collected, so there is a trade off between efficient memory usage with [method: Page.requests] and the amount of available information reported through [event: Page.request].

Returns:

  • (Array[untyped])


1163
1164
1165
# File 'lib/playwright_api/page.rb', line 1163

def requests
  wrap_impl(@impl.requests)
end

#route(url, handler, times: nil) ⇒ Object

Routing provides the capability to modify network requests that are made by a page.

Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.

NOTE: The handler will only be called for the first url if the response is a redirect.

NOTE: [method: Page.route] will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by setting serviceWorkers to 'block'.

NOTE: [method: Page.route] will not intercept the first request of a popup page. Use [method: BrowserContext.route] instead.

Usage

An example of a naive handler that aborts all image requests:

page = browser.new_page()
page.route("**/*.{png,jpg,jpeg}", lambda route: route.abort())
page.goto("https://example.com")
browser.close()

or the same snippet using a regex pattern instead:

page = browser.new_page()
page.route(re.compile(r"(\.png$)|(\.jpg$)"), lambda route: route.abort())
page.goto("https://example.com")
browser.close()

It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:

def handle_route(route: Route):
  if ("my-string" in route.request.post_data):
    route.fulfill(body="mocked-data")
  else:
    route.continue_()
page.route("/api/**", handle_route)

If a request matches multiple registered routes, the most recently registered route takes precedence.

Page routes take precedence over browser context routes (set up with [method: BrowserContext.route]) when request matches both handlers.

To remove a route with its handler you can use [method: Page.unroute].

NOTE: Enabling routing disables http cache.

Parameters:

  • url (String, Regexp, function)
  • handler (function)
  • times: (Integer) (defaults to: nil)

Returns:

  • (Object)


1301
1302
1303
# File 'lib/playwright_api/page.rb', line 1301

def route(url, handler, times: nil)
  wrap_impl(@impl.route(unwrap_impl(url), unwrap_impl(handler), times: unwrap_impl(times)))
end

#route_from_har(har, notFound: nil, update: nil, updateContent: nil, updateMode: nil, url: nil) ⇒ void

This method returns an undefined value.

If specified the network requests that are made in the page will be served from the HAR file. Read more about Replaying from HAR.

Playwright will not serve requests intercepted by Service Worker from the HAR file. See this issue. We recommend disabling Service Workers when using request interception by setting serviceWorkers to 'block'.

Parameters:

  • har (String, File)
  • notFound: ("abort", "fallback") (defaults to: nil)
  • update: (Boolean) (defaults to: nil)
  • updateContent: ("embed", "attach") (defaults to: nil)
  • updateMode: ("full", "minimal") (defaults to: nil)
  • url: (String, Regexp) (defaults to: nil)


1309
1310
1311
1312
1313
1314
1315
1316
1317
# File 'lib/playwright_api/page.rb', line 1309

def route_from_har(
      har,
      notFound: nil,
      update: nil,
      updateContent: nil,
      updateMode: nil,
      url: nil)
  wrap_impl(@impl.route_from_har(unwrap_impl(har), notFound: unwrap_impl(notFound), update: unwrap_impl(update), updateContent: unwrap_impl(updateContent), updateMode: unwrap_impl(updateMode), url: unwrap_impl(url)))
end

#route_web_socket(url, handler) ⇒ Object

This method allows to modify websocket connections that are made by the page.

Note that only WebSockets created after this method was called will be routed. It is recommended to call this method before navigating the page.

Usage

Below is an example of a simple mock that responds to a single message. See WebSocketRoute for more details and examples.

def message_handler(ws: WebSocketRoute, message: Union[str, bytes]):
  if message == "request":
    ws.send("response")

def handler(ws: WebSocketRoute):
  ws.on_message(lambda message: message_handler(ws, message))

page.route_web_socket("/ws", handler)

Raises:

  • (NotImplementedError)


1338
1339
1340
# File 'lib/playwright_api/page.rb', line 1338

def route_web_socket(url, handler)
  raise NotImplementedError.new('route_web_socket is not implemented yet.')
end

#screenshot(animations: nil, caret: nil, clip: nil, fullPage: nil, mask: nil, maskColor: nil, omitBackground: nil, path: nil, quality: nil, scale: nil, style: nil, timeout: nil, type: nil) ⇒ String

Returns the buffer with the captured screenshot.

Parameters:

  • animations: ("disabled", "allow") (defaults to: nil)
  • caret: ("hide", "initial") (defaults to: nil)
  • clip: (Hash[untyped, untyped]) (defaults to: nil)
  • fullPage: (Boolean) (defaults to: nil)
  • mask: (Array[untyped]) (defaults to: nil)
  • maskColor: (String) (defaults to: nil)
  • omitBackground: (Boolean) (defaults to: nil)
  • path: (String, File) (defaults to: nil)
  • quality: (Integer) (defaults to: nil)
  • scale: ("css", "device") (defaults to: nil)
  • style: (String) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)
  • type: ("png", "jpeg") (defaults to: nil)

Returns:

  • (String)


1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
# File 'lib/playwright_api/page.rb', line 1344

def screenshot(
      animations: nil,
      caret: nil,
      clip: nil,
      fullPage: nil,
      mask: nil,
      maskColor: nil,
      omitBackground: nil,
      path: nil,
      quality: nil,
      scale: nil,
      style: nil,
      timeout: nil,
      type: nil)
  wrap_impl(@impl.screenshot(animations: unwrap_impl(animations), caret: unwrap_impl(caret), clip: unwrap_impl(clip), fullPage: unwrap_impl(fullPage), mask: unwrap_impl(mask), maskColor: unwrap_impl(maskColor), omitBackground: unwrap_impl(omitBackground), path: unwrap_impl(path), quality: unwrap_impl(quality), scale: unwrap_impl(scale), style: unwrap_impl(style), timeout: unwrap_impl(timeout), type: unwrap_impl(type)))
end

#select_option(selector, element: nil, index: nil, value: nil, label: nil, force: nil, noWaitAfter: nil, strict: nil, timeout: nil) ⇒ Array[untyped]

This method waits for an element matching selector, waits for actionability checks, waits until all specified options are present in the <select> element and selects these options.

If the target element is not a <select> element, this method throws an error. However, if the element is inside the <label> element that has an associated control, the control will be used instead.

Returns the array of option values that have been successfully selected.

Triggers a change and input event once all the provided options have been selected.

Usage

# Single selection matching the value or label
page.select_option("select#colors", "blue")
# single selection matching both the label
page.select_option("select#colors", label="blue")
# multiple selection
page.select_option("select#colors", value=["red", "green", "blue"])

Parameters:

  • selector (String)
  • element: (ElementHandle, Array[untyped]) (defaults to: nil)
  • index: (Integer, Array[untyped]) (defaults to: nil)
  • value: (String, Array[untyped]) (defaults to: nil)
  • label: (String, Array[untyped]) (defaults to: nil)
  • force: (Boolean) (defaults to: nil)
  • noWaitAfter: (Boolean) (defaults to: nil)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Returns:

  • (Array[untyped])


1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
# File 'lib/playwright_api/page.rb', line 1380

def select_option(
      selector,
      element: nil,
      index: nil,
      value: nil,
      label: nil,
      force: nil,
      noWaitAfter: nil,
      strict: nil,
      timeout: nil)
  wrap_impl(@impl.select_option(unwrap_impl(selector), element: unwrap_impl(element), index: unwrap_impl(index), value: unwrap_impl(value), label: unwrap_impl(label), force: unwrap_impl(force), noWaitAfter: unwrap_impl(noWaitAfter), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout)))
end

#set_checked(selector, checked, force: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) ⇒ void

This method returns an undefined value.

This method checks or unchecks an element matching selector by performing the following steps:

  1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
  2. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
  3. If the element already has the right checked state, this method returns immediately.
  4. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
  5. Scroll the element into view if needed.
  6. Use [property: Page.mouse] to click in the center of the element.
  7. Ensure that the element is now checked or unchecked. If not, this method throws.

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

Parameters:

  • selector (String)
  • checked (Boolean)
  • force: (Boolean) (defaults to: nil)
  • noWaitAfter: (Boolean) (defaults to: nil)
  • position: (Hash[untyped, untyped]) (defaults to: nil)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)
  • trial: (Boolean) (defaults to: nil)


1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
# File 'lib/playwright_api/page.rb', line 1405

def set_checked(
      selector,
      checked,
      force: nil,
      noWaitAfter: nil,
      position: nil,
      strict: nil,
      timeout: nil,
      trial: nil)
  wrap_impl(@impl.set_checked(unwrap_impl(selector), unwrap_impl(checked), force: unwrap_impl(force), noWaitAfter: unwrap_impl(noWaitAfter), position: unwrap_impl(position), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout), trial: unwrap_impl(trial)))
end

#set_content(html, timeout: nil, waitUntil: nil) ⇒ void Also known as: content=

This method returns an undefined value.

This method internally calls document.write(), inheriting all its specific characteristics and behaviors.

Parameters:

  • html (String)
  • timeout: (Float) (defaults to: nil)
  • waitUntil: ("load", "domcontentloaded", "networkidle", "commit") (defaults to: nil)


1419
1420
1421
# File 'lib/playwright_api/page.rb', line 1419

def set_content(html, timeout: nil, waitUntil: nil)
  wrap_impl(@impl.set_content(unwrap_impl(html), timeout: unwrap_impl(timeout), waitUntil: unwrap_impl(waitUntil)))
end

#set_default_navigation_timeout(timeout) ⇒ void Also known as: default_navigation_timeout=

This method returns an undefined value.

This setting will change the default maximum navigation time for the following methods and related shortcuts:

  • [method: Page.goBack]
  • [method: Page.goForward]
  • [method: Page.goto]
  • [method: Page.reload]
  • [method: Page.setContent]
  • [method: Page.waitForNavigation]
  • [method: Page.waitForURL]

NOTE: [method: Page.setDefaultNavigationTimeout] takes priority over [method: Page.setDefaultTimeout], [method: BrowserContext.setDefaultTimeout] and [method: BrowserContext.setDefaultNavigationTimeout].

Parameters:

  • timeout (Float)


1436
1437
1438
# File 'lib/playwright_api/page.rb', line 1436

def set_default_navigation_timeout(timeout)
  wrap_impl(@impl.set_default_navigation_timeout(unwrap_impl(timeout)))
end

#set_default_timeout(timeout) ⇒ void Also known as: default_timeout=

This method returns an undefined value.

This setting will change the default maximum time for all the methods accepting timeout option.

NOTE: [method: Page.setDefaultNavigationTimeout] takes priority over [method: Page.setDefaultTimeout].

Parameters:

  • timeout (Float)


1445
1446
1447
# File 'lib/playwright_api/page.rb', line 1445

def set_default_timeout(timeout)
  wrap_impl(@impl.set_default_timeout(unwrap_impl(timeout)))
end

#set_extra_http_headers(headers) ⇒ void Also known as: extra_http_headers=

This method returns an undefined value.

The extra HTTP headers will be sent with every request the page initiates.

NOTE: [method: Page.setExtraHTTPHeaders] does not guarantee the order of headers in the outgoing requests.

Parameters:

  • headers (Hash[untyped, untyped])


1454
1455
1456
# File 'lib/playwright_api/page.rb', line 1454

def set_extra_http_headers(headers)
  wrap_impl(@impl.set_extra_http_headers(unwrap_impl(headers)))
end

#set_input_files(selector, files, noWaitAfter: nil, strict: nil, timeout: nil) ⇒ void

This method returns an undefined value.

Sets the value of the file input to these file paths or files. If some of the filePaths are relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with a [webkitdirectory] attribute, only a single directory path is supported.

This method expects selector to point to an input element. However, if the element is inside the <label> element that has an associated control, targets the control instead.

Parameters:

  • selector (String)
  • files ((String | File), Array[untyped], Hash[untyped, untyped], Array[untyped])
  • noWaitAfter: (Boolean) (defaults to: nil)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)


1466
1467
1468
1469
1470
1471
1472
1473
# File 'lib/playwright_api/page.rb', line 1466

def set_input_files(
      selector,
      files,
      noWaitAfter: nil,
      strict: nil,
      timeout: nil)
  wrap_impl(@impl.set_input_files(unwrap_impl(selector), unwrap_impl(files), noWaitAfter: unwrap_impl(noWaitAfter), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout)))
end

#set_viewport_size(viewportSize) ⇒ void Also known as: viewport_size=

This method returns an undefined value.

In the case of multiple pages in a single browser, each page can have its own viewport size. However, [method: Browser.newContext] allows to set viewport size (and more) for all pages in the context at once.

[method: Page.setViewportSize] will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport size before navigating to the page. [method: Page.setViewportSize] will also reset screen size, use [method: Browser.newContext] with screen and viewport parameters if you need better control of these properties.

Usage

page = browser.new_page()
page.set_viewport_size({"width": 640, "height": 480})
page.goto("https://example.com")

Parameters:

  • viewportSize (Hash[untyped, untyped])


1489
1490
1491
# File 'lib/playwright_api/page.rb', line 1489

def set_viewport_size(viewportSize)
  wrap_impl(@impl.set_viewport_size(unwrap_impl(viewportSize)))
end

#snapshot_for_ai(timeout: nil, depth: nil, boxes: nil, _track: nil) ⇒ Object



1894
1895
1896
# File 'lib/playwright_api/page.rb', line 1894

def snapshot_for_ai(timeout: nil, depth: nil, boxes: nil, _track: nil)
  wrap_impl(@impl.snapshot_for_ai(timeout: unwrap_impl(timeout), depth: unwrap_impl(depth), boxes: unwrap_impl(boxes), _track: unwrap_impl(_track)))
end

#start_css_coverage(resetOnNavigation: nil, reportAnonymousScripts: nil) ⇒ Object



1889
1890
1891
# File 'lib/playwright_api/page.rb', line 1889

def start_css_coverage(resetOnNavigation: nil, reportAnonymousScripts: nil)
  wrap_impl(@impl.start_css_coverage(resetOnNavigation: unwrap_impl(resetOnNavigation), reportAnonymousScripts: unwrap_impl(reportAnonymousScripts)))
end

#start_js_coverage(resetOnNavigation: nil, reportAnonymousScripts: nil) ⇒ Object



1904
1905
1906
# File 'lib/playwright_api/page.rb', line 1904

def start_js_coverage(resetOnNavigation: nil, reportAnonymousScripts: nil)
  wrap_impl(@impl.start_js_coverage(resetOnNavigation: unwrap_impl(resetOnNavigation), reportAnonymousScripts: unwrap_impl(reportAnonymousScripts)))
end

#stop_css_coverageObject



1909
1910
1911
# File 'lib/playwright_api/page.rb', line 1909

def stop_css_coverage
  wrap_impl(@impl.stop_css_coverage)
end

#stop_js_coverageObject



1899
1900
1901
# File 'lib/playwright_api/page.rb', line 1899

def stop_js_coverage
  wrap_impl(@impl.stop_js_coverage)
end

#tap_point(selector, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) ⇒ void

This method returns an undefined value.

This method taps an element matching selector by performing the following steps:

  1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
  2. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
  3. Scroll the element into view if needed.
  4. Use [property: Page.touchscreen] to tap the center of the element, or the specified position.

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

NOTE: [method: Page.tap] will throw if the hasTouch option of the browser context is false.

Parameters:

  • selector (String)
  • force: (Boolean) (defaults to: nil)
  • modifiers: (Array[untyped]) (defaults to: nil)
  • noWaitAfter: (Boolean) (defaults to: nil)
  • position: (Hash[untyped, untyped]) (defaults to: nil)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)
  • trial: (Boolean) (defaults to: nil)


1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
# File 'lib/playwright_api/page.rb', line 1511

def tap_point(
      selector,
      force: nil,
      modifiers: nil,
      noWaitAfter: nil,
      position: nil,
      strict: nil,
      timeout: nil,
      trial: nil)
  wrap_impl(@impl.tap_point(unwrap_impl(selector), force: unwrap_impl(force), modifiers: unwrap_impl(modifiers), noWaitAfter: unwrap_impl(noWaitAfter), position: unwrap_impl(position), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout), trial: unwrap_impl(trial)))
end

#text_content(selector, strict: nil, timeout: nil) ⇒ nil, String

Returns element.textContent.

Parameters:

  • selector (String)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Returns:

  • (nil, String)


1525
1526
1527
# File 'lib/playwright_api/page.rb', line 1525

def text_content(selector, strict: nil, timeout: nil)
  wrap_impl(@impl.text_content(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout)))
end

#titleString

Returns the page's title.

Returns:

  • (String)


1531
1532
1533
# File 'lib/playwright_api/page.rb', line 1531

def title
  wrap_impl(@impl.title)
end

#type(selector, text, delay: nil, noWaitAfter: nil, strict: nil, timeout: nil) ⇒ void

Deprecated.

In most cases, you should use [method: Locator.fill] instead. You only need to press keys one by one if there is special keyboard handling on the page - in this case use [method: Locator.pressSequentially].

This method returns an undefined value.

Sends a keydown, keypress/input, and keyup event for each character in the text. page.type can be used to send fine-grained keyboard events. To fill values in form fields, use [method: Page.fill].

To press a special key, like Control or ArrowDown, use [method: Keyboard.press].

Usage

Parameters:

  • selector (String)
  • text (String)
  • delay: (Float) (defaults to: nil)
  • noWaitAfter: (Boolean) (defaults to: nil)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)


1544
1545
1546
1547
1548
1549
1550
1551
1552
# File 'lib/playwright_api/page.rb', line 1544

def type(
      selector,
      text,
      delay: nil,
      noWaitAfter: nil,
      strict: nil,
      timeout: nil)
  wrap_impl(@impl.type(unwrap_impl(selector), unwrap_impl(text), delay: unwrap_impl(delay), noWaitAfter: unwrap_impl(noWaitAfter), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout)))
end

#uncheck(selector, force: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) ⇒ void

This method returns an undefined value.

This method unchecks an element matching selector by performing the following steps:

  1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
  2. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already unchecked, this method returns immediately.
  3. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
  4. Scroll the element into view if needed.
  5. Use [property: Page.mouse] to click in the center of the element.
  6. Ensure that the element is now unchecked. If not, this method throws.

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

Parameters:

  • selector (String)
  • force: (Boolean) (defaults to: nil)
  • noWaitAfter: (Boolean) (defaults to: nil)
  • position: (Hash[untyped, untyped]) (defaults to: nil)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)
  • trial: (Boolean) (defaults to: nil)


1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
# File 'lib/playwright_api/page.rb', line 1565

def uncheck(
      selector,
      force: nil,
      noWaitAfter: nil,
      position: nil,
      strict: nil,
      timeout: nil,
      trial: nil)
  wrap_impl(@impl.uncheck(unwrap_impl(selector), force: unwrap_impl(force), noWaitAfter: unwrap_impl(noWaitAfter), position: unwrap_impl(position), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout), trial: unwrap_impl(trial)))
end

#unroute(url, handler: nil) ⇒ void

This method returns an undefined value.

Removes a route created with [method: Page.route]. When handler is not specified, removes all routes for the url.

Parameters:

  • url (String, Regexp, function)
  • handler: (function) (defaults to: nil)


1585
1586
1587
# File 'lib/playwright_api/page.rb', line 1585

def unroute(url, handler: nil)
  wrap_impl(@impl.unroute(unwrap_impl(url), handler: unwrap_impl(handler)))
end

#unroute_all(behavior: nil) ⇒ void

This method returns an undefined value.

Removes all routes created with [method: Page.route] and [method: Page.routeFromHAR].

Parameters:

  • behavior: ("wait", "ignoreErrors", "default") (defaults to: nil)


1578
1579
1580
# File 'lib/playwright_api/page.rb', line 1578

def unroute_all(behavior: nil)
  wrap_impl(@impl.unroute_all(behavior: unwrap_impl(behavior)))
end

#urlString

Returns:

  • (String)


1589
1590
1591
# File 'lib/playwright_api/page.rb', line 1589

def url
  wrap_impl(@impl.url)
end

#videonil, untyped

Video object associated with this page. Can be used to access the video file when using the recordVideo context option.

Returns:

  • (nil, untyped)


1595
1596
1597
# File 'lib/playwright_api/page.rb', line 1595

def video
  wrap_impl(@impl.video)
end

#viewport_sizenil, Hash[untyped, untyped]

Returns:

  • (nil, Hash[untyped, untyped])


1599
1600
1601
# File 'lib/playwright_api/page.rb', line 1599

def viewport_size
  wrap_impl(@impl.viewport_size)
end

#visible?(selector, strict: nil, timeout: nil) ⇒ Boolean

Returns whether the element is visible. selector that does not match any elements is considered not visible.

Parameters:

  • selector (String)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Returns:

  • (Boolean)


952
953
954
# File 'lib/playwright_api/page.rb', line 952

def visible?(selector, strict: nil, timeout: nil)
  wrap_impl(@impl.visible?(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout)))
end

#wait_for_event(event, predicate: nil, timeout: nil) ⇒ Object

NOTE: In most cases, you should use [method: Page.waitForEvent].

Waits for given event to fire. If predicate is provided, it passes event's value into the predicate function and waits for predicate(event) to return a truthy value. Will throw an error if the page is closed before the event is fired.

Raises:

  • (NotImplementedError)


1879
1880
1881
# File 'lib/playwright_api/page.rb', line 1879

def wait_for_event(event, predicate: nil, timeout: nil)
  raise NotImplementedError.new('wait_for_event is not implemented yet.')
end

#wait_for_function(expression, arg: nil, polling: nil, timeout: nil) ⇒ JSHandle

Returns when the expression returns a truthy value. It resolves to a JSHandle of the truthy value.

Usage

The [method: Page.waitForFunction] can be used to observe viewport size change:

from playwright.sync_api import sync_playwright, Playwright

def run(playwright: Playwright):
    webkit = playwright.webkit
    browser = webkit.launch()
    page = browser.new_page()
    page.evaluate("window.x = 0; setTimeout(() => { window.x = 100 }, 1000);")
    page.wait_for_function("() => window.x > 0")
    browser.close()

with sync_playwright() as playwright:
    run(playwright)

To pass an argument to the predicate of [method: Page.waitForFunction] function:

selector = ".foo"
page.wait_for_function("selector => !!document.querySelector(selector)", selector)

Parameters:

  • expression (String)
  • arg: (Object) (defaults to: nil)
  • polling: (Float, "raf") (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Returns:



1670
1671
1672
# File 'lib/playwright_api/page.rb', line 1670

def wait_for_function(expression, arg: nil, polling: nil, timeout: nil)
  wrap_impl(@impl.wait_for_function(unwrap_impl(expression), arg: unwrap_impl(arg), polling: unwrap_impl(polling), timeout: unwrap_impl(timeout)))
end

#wait_for_load_state(state: nil, timeout: nil) ⇒ void

This method returns an undefined value.

Returns when the required load state has been reached.

This resolves when the page reaches a required load state, load by default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.

NOTE: Most of the time, this method is not needed because Playwright auto-waits before every action.

Usage

page.get_by_role("button").click() # click triggers navigation.
page.wait_for_load_state() # the promise resolves after "load" event.
with page.expect_popup() as page_info:
    page.get_by_role("button").click() # click triggers a popup.
popup = page_info.value
# Wait for the "DOMContentLoaded" event.
popup.wait_for_load_state("domcontentloaded")
print(popup.title()) # popup is ready to use.

Parameters:

  • state: ("load", "domcontentloaded", "networkidle") (defaults to: nil)
  • timeout: (Float) (defaults to: nil)


1697
1698
1699
# File 'lib/playwright_api/page.rb', line 1697

def wait_for_load_state(state: nil, timeout: nil)
  wrap_impl(@impl.wait_for_load_state(state: unwrap_impl(state), timeout: unwrap_impl(timeout)))
end

#wait_for_selector(selector, state: nil, strict: nil, timeout: nil) ⇒ nil, ElementHandle

Returns when element specified by selector satisfies state option. Returns null if waiting for hidden or detached.

NOTE: Playwright automatically waits for element to be ready before performing an action. Using Locator objects and web-first assertions makes the code wait-for-selector-free.

Wait for the selector to satisfy state option (either appear/disappear from dom, or become visible/hidden). If at the moment of calling the method selector already satisfies the condition, the method will return immediately. If the selector doesn't satisfy the condition for the timeout milliseconds, the function will throw.

Usage

This method works across navigations:

from playwright.sync_api import sync_playwright, Playwright

def run(playwright: Playwright):
    chromium = playwright.chromium
    browser = chromium.launch()
    page = browser.new_page()
    for current_url in ["https://google.com", "https://bbc.com"]:
        page.goto(current_url, wait_until="domcontentloaded")
        element = page.wait_for_selector("img")
        print("Loaded image: " + str(element.get_attribute("src")))
    browser.close()

with sync_playwright() as playwright:
    run(playwright)

Parameters:

  • selector (String)
  • state: ("attached", "detached", "visible", "hidden") (defaults to: nil)
  • strict: (Boolean) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Returns:



1815
1816
1817
# File 'lib/playwright_api/page.rb', line 1815

def wait_for_selector(selector, state: nil, strict: nil, timeout: nil)
  wrap_impl(@impl.wait_for_selector(unwrap_impl(selector), state: unwrap_impl(state), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout)))
end

#wait_for_timeout(timeout) ⇒ void

This method returns an undefined value.

Waits for the given timeout in milliseconds.

Note that page.waitForTimeout() should only be used for debugging. Tests using the timer in production are going to be flaky. Use signals such as network events, selectors becoming visible and others instead.

Usage

# wait for 1 second
page.wait_for_timeout(1000)

Parameters:

  • timeout (Float)


1831
1832
1833
# File 'lib/playwright_api/page.rb', line 1831

def wait_for_timeout(timeout)
  wrap_impl(@impl.wait_for_timeout(unwrap_impl(timeout)))
end

#wait_for_url(url, timeout: nil, waitUntil: nil) ⇒ void

This method returns an undefined value.

Waits for the main frame to navigate to the given URL.

Usage

page.click("a.delayed-navigation") # clicking the link will indirectly cause a navigation
page.wait_for_url("**/target.html")

Parameters:

  • url (String, Regexp, function)
  • timeout: (Float) (defaults to: nil)
  • waitUntil: ("load", "domcontentloaded", "networkidle", "commit") (defaults to: nil)


1844
1845
1846
# File 'lib/playwright_api/page.rb', line 1844

def wait_for_url(url, timeout: nil, waitUntil: nil)
  wrap_impl(@impl.wait_for_url(unwrap_impl(url), timeout: unwrap_impl(timeout), waitUntil: unwrap_impl(waitUntil)))
end

#workersArray[untyped]

This method returns all of the dedicated WebWorkers associated with the page.

NOTE: This does not contain ServiceWorkers

Returns:

  • (Array[untyped])


1869
1870
1871
# File 'lib/playwright_api/page.rb', line 1869

def workers
  wrap_impl(@impl.workers)
end