Class: Playwright::Page
- Inherits:
-
PlaywrightApi
- Object
- PlaywrightApi
- Playwright::Page
- Defined in:
- lib/playwright_api/page.rb
Overview
-
extends: [EventEmitter](nodejs.org/api/events.html#events_class_eventemitter)
Page provides methods to interact with a single tab in a ‘Browser`, or an
- extension background page](developer.chrome.com/extensions/background_pages) 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:
“‘js const { webkit } = require(’playwright’); // Or ‘chromium’ or ‘firefox’.
(async () =>
const browser = await webkit.launch(); const context = await browser.newContext(); const page = await context.newPage(); await page.goto('https://example.com'); await page.screenshot({path: 'screenshot.png'); await browser.close();})(); “‘
The Page class emits various events (described below) which can be handled using any of Node’s native [‘EventEmitter`](nodejs.org/api/events.html#events_class_eventemitter) methods, such as `on`, `once` or `removeListener`.
This example logs a message for a single page ‘load` event:
“‘js page.once(’load’, () => console.log(‘Page loaded!’)); “‘
To unsubscribe from events use the ‘removeListener` method:
“‘js function logRequest(interceptedRequest) {
console.log('A request was made:', interceptedRequest.url());} page.on(‘request’, logRequest); // Sometime later… page.removeListener(‘request’, logRequest); “‘
Instance Method Summary collapse
-
#accessibility ⇒ Object
property.
-
#add_init_script(script, arg: nil) ⇒ Object
Adds a script which would be evaluated in one of the following scenarios: - Whenever the page is navigated.
-
#add_script_tag(content: nil, path: nil, type: nil, url: nil) ⇒ Object
Adds a ‘<script>` tag into the page with the desired url or content.
-
#add_style_tag(content: nil, path: nil, url: nil) ⇒ Object
Adds a ‘<link rel=“stylesheet”>` tag into the page with the desired url or a `<style type=“text/css”>` tag with the content.
- #after_initialize ⇒ Object
-
#bring_to_front ⇒ Object
Brings page to front (activates tab).
-
#check(selector, force: nil, noWaitAfter: nil, timeout: nil) ⇒ Object
This method checks an element matching ‘selector` by performing the following steps: 1.
-
#checked?(selector, timeout: nil) ⇒ Boolean
Returns whether the element is checked.
-
#click(selector, button: nil, clickCount: nil, delay: nil, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, timeout: nil) ⇒ Object
This method clicks an element matching ‘selector` by performing the following steps: 1.
-
#close(runBeforeUnload: nil) ⇒ Object
If ‘runBeforeUnload` is `false`, does not run any unload handlers and waits for the page to be closed.
-
#closed? ⇒ Boolean
Indicates that the page has been closed.
-
#content ⇒ Object
Gets the full HTML contents of the page, including the doctype.
-
#context ⇒ Object
Get the browser context that the page belongs to.
-
#coverage ⇒ Object
Browser-specific Coverage implementation, only available for Chromium atm.
-
#dblclick(selector, button: nil, delay: nil, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, timeout: nil) ⇒ Object
This method double clicks an element matching ‘selector` by performing the following steps: 1.
-
#disabled?(selector, timeout: nil) ⇒ Boolean
Returns whether the element is disabled, the opposite of [enabled](./actionability.md#enabled).
-
#dispatch_event(selector, type, eventInit: nil, timeout: nil) ⇒ Object
The snippet below dispatches the ‘click` event on the element.
-
#editable?(selector, timeout: nil) ⇒ Boolean
Returns whether the element is [editable](./actionability.md#editable).
-
#emulate_media(params) ⇒ Object
“‘js await page.evaluate(() => matchMedia(’screen’).matches); // → true await page.evaluate(() => matchMedia(‘print’).matches); // → false.
-
#enabled?(selector, timeout: nil) ⇒ Boolean
Returns whether the element is [enabled](./actionability.md#enabled).
-
#eval_on_selector(selector, pageFunction, arg: nil) ⇒ Object
The method finds an element matching the specified selector within the page and passes it as a first argument to ‘pageFunction`.
-
#eval_on_selector_all(selector, pageFunction, 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 ‘pageFunction`.
-
#evaluate(pageFunction, arg: nil) ⇒ Object
Returns the value of the ‘pageFunction` invocation.
-
#evaluate_handle(pageFunction, arg: nil) ⇒ Object
Returns the value of the ‘pageFunction` invocation as in-page object (JSHandle).
-
#expose_binding(name, callback, handle: nil) ⇒ Object
The method adds a function called ‘name` on the `window` object of every frame in this page.
-
#expose_function(name, callback) ⇒ Object
The method adds a function called ‘name` on the `window` object of every frame in the page.
-
#fill(selector, value, noWaitAfter: nil, timeout: nil) ⇒ Object
This method waits for an element matching ‘selector`, waits for [actionability](./actionability.md) checks, focuses the element, fills it and triggers an `input` event after filling.
-
#focus(selector, timeout: nil) ⇒ Object
This method fetches an element with ‘selector` and focuses it.
-
#frame(frameSelector) ⇒ Object
Returns frame matching the specified criteria.
-
#frames ⇒ Object
An array of all frames attached to the page.
-
#get_attribute(selector, name, timeout: nil) ⇒ Object
Returns element attribute value.
-
#go_back(timeout: nil, waitUntil: nil) ⇒ Object
Returns the main resource response.
-
#go_forward(timeout: nil, waitUntil: nil) ⇒ Object
Returns the main resource response.
-
#goto(url, referer: nil, timeout: nil, waitUntil: nil) ⇒ Object
Returns the main resource response.
-
#hidden?(selector, timeout: nil) ⇒ Boolean
Returns whether the element is hidden, the opposite of [visible](./actionability.md#visible).
-
#hover(selector, force: nil, modifiers: nil, position: nil, timeout: nil) ⇒ Object
This method hovers over an element matching ‘selector` by performing the following steps: 1.
-
#inner_html(selector, timeout: nil) ⇒ Object
Returns ‘element.innerHTML`.
-
#inner_text(selector, timeout: nil) ⇒ Object
Returns ‘element.innerText`.
-
#keyboard ⇒ Object
property.
-
#main_frame ⇒ Object
The page’s main frame.
-
#mouse ⇒ Object
property.
-
#opener ⇒ Object
Returns the opener for popup pages and ‘null` for others.
- #owned_context=(req) ⇒ Object
-
#pdf(displayHeaderFooter: nil, footerTemplate: nil, format: nil, headerTemplate: nil, height: nil, landscape: nil, margin: nil, pageRanges: nil, path: nil, preferCSSPageSize: nil, printBackground: nil, scale: nil, width: nil) ⇒ Object
Returns the PDF buffer.
-
#press(selector, key, delay: nil, noWaitAfter: nil, timeout: nil) ⇒ Object
Focuses the element, and then uses [‘method: Keyboard.down`] and [`method: Keyboard.up`].
-
#query_selector(selector) ⇒ Object
The method finds an element matching the specified selector within the page.
-
#query_selector_all(selector) ⇒ Object
The method finds all elements matching the specified selector within the page.
-
#reload(timeout: nil, waitUntil: nil) ⇒ Object
Returns the main resource response.
-
#route(url, handler) ⇒ Object
Routing provides the capability to modify network requests that are made by a page.
-
#screenshot(clip: nil, fullPage: nil, omitBackground: nil, path: nil, quality: nil, timeout: nil, type: nil) ⇒ Object
Returns the buffer with the captured screenshot.
-
#select_option(selector, values, noWaitAfter: nil, timeout: nil) ⇒ Object
Returns the array of option values that have been successfully selected.
- #set_content(html, timeout: nil, waitUntil: nil) ⇒ Object
-
#set_default_navigation_timeout(timeout) ⇒ Object
(also: #default_navigation_timeout=)
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`].
-
#set_default_timeout(timeout) ⇒ Object
(also: #default_timeout=)
This setting will change the default maximum time for all the methods accepting ‘timeout` option.
-
#set_extra_http_headers(headers) ⇒ Object
(also: #extra_http_headers=)
The extra HTTP headers will be sent with every request the page initiates.
-
#set_input_files(selector, files, noWaitAfter: nil, timeout: nil) ⇒ Object
This method expects ‘selector` to point to an [input element](developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
-
#set_viewport_size(viewportSize) ⇒ Object
(also: #viewport_size=)
In the case of multiple pages in a single browser, each page can have its own viewport size.
-
#tap_point(selector, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, timeout: nil) ⇒ Object
This method taps an element matching ‘selector` by performing the following steps: 1.
-
#text_content(selector, timeout: nil) ⇒ Object
Returns ‘element.textContent`.
-
#title ⇒ Object
Returns the page’s title.
-
#touchscreen ⇒ Object
property.
-
#type_text(selector, text, delay: nil, noWaitAfter: nil, timeout: nil) ⇒ Object
Sends a ‘keydown`, `keypress`/`input`, and `keyup` event for each character in the text.
-
#uncheck(selector, force: nil, noWaitAfter: nil, timeout: nil) ⇒ Object
This method unchecks an element matching ‘selector` by performing the following steps: 1.
-
#unroute(url, handler: nil) ⇒ Object
Removes a route created with [‘method: Page.route`].
-
#url ⇒ Object
Shortcut for main frame’s [‘method: Frame.url`].
-
#video ⇒ Object
Video object associated with this page.
- #viewport_size ⇒ Object
-
#visible?(selector, timeout: nil) ⇒ Boolean
Returns whether the element is [visible](./actionability.md#visible).
-
#wait_for_event(event, optionsOrPredicate: nil) ⇒ Object
Returns the event data value.
-
#wait_for_function(pageFunction, arg: nil, polling: nil, timeout: nil) ⇒ Object
Returns when the ‘pageFunction` returns a truthy value.
-
#wait_for_load_state(state: nil, timeout: nil) ⇒ Object
Returns when the required load state has been reached.
-
#wait_for_navigation(timeout: nil, url: nil, waitUntil: nil) ⇒ Object
Returns the main resource response.
-
#wait_for_request(urlOrPredicate, timeout: nil) ⇒ Object
Waits for the matching request and returns it.
-
#wait_for_response(urlOrPredicate, timeout: nil) ⇒ Object
Returns the matched response.
-
#wait_for_selector(selector, state: nil, timeout: nil) ⇒ Object
Returns when element specified by selector satisfies ‘state` option.
-
#wait_for_timeout(timeout) ⇒ Object
Waits for the given ‘timeout` in milliseconds.
-
#workers ⇒ Object
This method returns all of the dedicated [WebWorkers](developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) associated with the page.
Methods inherited from PlaywrightApi
Instance Method Details
#accessibility ⇒ Object
property
48 49 50 |
# File 'lib/playwright_api/page.rb', line 48 def accessibility # property wrap_channel_owner(@channel_owner.accessibility) end |
#add_init_script(script, arg: 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`.
An example of overriding ‘Math.random` before the page loads:
“‘js // preload.js Math.random = () => 42;
// In your playwright script, assuming the preload.js file is in same directory const preloadFile = fs.readFileSync(‘./preload.js’, ‘utf8’); await page.addInitScript(preloadFile); “‘
> NOTE The order of evaluation of multiple scripts installed via [‘method: BrowserContext.addInitScript`] and
- ‘method: Page.addInitScript`
-
is not defined.
144 145 146 |
# File 'lib/playwright_api/page.rb', line 144 def add_init_script(script, arg: nil) raise NotImplementedError.new('add_init_script is not implemented yet.') end |
#add_script_tag(content: nil, path: nil, type: nil, url: nil) ⇒ Object
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.
Shortcut for main frame’s [‘method: Frame.addScriptTag`].
152 153 154 |
# File 'lib/playwright_api/page.rb', line 152 def add_script_tag(content: nil, path: nil, type: nil, url: nil) raise NotImplementedError.new('add_script_tag is not implemented yet.') end |
#add_style_tag(content: nil, path: nil, url: nil) ⇒ Object
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.
Shortcut for main frame’s [‘method: Frame.addStyleTag`].
160 161 162 |
# File 'lib/playwright_api/page.rb', line 160 def add_style_tag(content: nil, path: nil, url: nil) raise NotImplementedError.new('add_style_tag is not implemented yet.') end |
#after_initialize ⇒ Object
1192 1193 1194 |
# File 'lib/playwright_api/page.rb', line 1192 def after_initialize wrap_channel_owner(@channel_owner.after_initialize) end |
#bring_to_front ⇒ Object
Brings page to front (activates tab).
165 166 167 |
# File 'lib/playwright_api/page.rb', line 165 def bring_to_front raise NotImplementedError.new('bring_to_front is not implemented yet.') end |
#check(selector, force: nil, noWaitAfter: nil, timeout: nil) ⇒ Object
This method checks an element matching ‘selector` by performing the following steps:
-
Find an element match matching ‘selector`. If there is none, wait until a matching element is attached to the DOM.
-
Ensure that matched element is a checkbox or a radio input. If not, this method rejects. If the element is already checked, this method returns immediately.
-
Wait for [actionability](./actionability.md) checks on the matched element, unless ‘force` option is set. If the element is detached during the checks, the whole action is retried.
-
Scroll the element into view if needed.
-
Use [‘property: Page.mouse`] to click in the center of the element.
-
Wait for initiated navigations to either succeed or fail, unless ‘noWaitAfter` option is set.
-
Ensure that the element is now checked. If not, this method rejects.
When all steps combined have not finished during the specified ‘timeout`, this method rejects with a `TimeoutError`. Passing zero timeout disables this.
Shortcut for main frame’s [‘method: Frame.check`].
184 185 186 |
# File 'lib/playwright_api/page.rb', line 184 def check(selector, force: nil, noWaitAfter: nil, timeout: nil) raise NotImplementedError.new('check is not implemented yet.') end |
#checked?(selector, timeout: nil) ⇒ Boolean
Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
636 637 638 |
# File 'lib/playwright_api/page.rb', line 636 def checked?(selector, timeout: nil) raise NotImplementedError.new('checked? is not implemented yet.') end |
#click(selector, button: nil, clickCount: nil, delay: nil, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, timeout: nil) ⇒ Object
This method clicks an element matching ‘selector` by performing the following steps:
-
Find an element match matching ‘selector`. If there is none, wait until a matching element is attached to the DOM.
-
Wait for [actionability](./actionability.md) checks on the matched element, unless ‘force` option is set. If the element is detached during the checks, the whole action is retried.
-
Scroll the element into view if needed.
-
Use [‘property: Page.mouse`] to click in the center of the element, or the specified `position`.
-
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 rejects with a `TimeoutError`. Passing zero timeout disables this.
Shortcut for main frame’s [‘method: Frame.click`].
200 201 202 203 204 205 206 207 208 209 210 211 |
# File 'lib/playwright_api/page.rb', line 200 def click( selector, button: nil, clickCount: nil, delay: nil, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, timeout: nil) raise NotImplementedError.new('click is not implemented yet.') end |
#close(runBeforeUnload: nil) ⇒ Object
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.
220 221 222 |
# File 'lib/playwright_api/page.rb', line 220 def close(runBeforeUnload: nil) raise NotImplementedError.new('close is not implemented yet.') end |
#closed? ⇒ Boolean
Indicates that the page has been closed.
641 642 643 |
# File 'lib/playwright_api/page.rb', line 641 def closed? raise NotImplementedError.new('closed? is not implemented yet.') end |
#content ⇒ Object
Gets the full HTML contents of the page, including the doctype.
225 226 227 |
# File 'lib/playwright_api/page.rb', line 225 def content raise NotImplementedError.new('content is not implemented yet.') end |
#context ⇒ Object
Get the browser context that the page belongs to.
230 231 232 |
# File 'lib/playwright_api/page.rb', line 230 def context raise NotImplementedError.new('context is not implemented yet.') end |
#coverage ⇒ Object
Browser-specific Coverage implementation, only available for Chromium atm. See ‘ChromiumCoverage`(#class-chromiumcoverage) for more details.
54 55 56 |
# File 'lib/playwright_api/page.rb', line 54 def coverage # property raise NotImplementedError.new('coverage is not implemented yet.') end |
#dblclick(selector, button: nil, delay: nil, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, timeout: nil) ⇒ Object
This method double clicks an element matching ‘selector` by performing the following steps:
-
Find an element match matching ‘selector`. If there is none, wait until a matching element is attached to the DOM.
-
Wait for [actionability](./actionability.md) checks on the matched element, unless ‘force` option is set. If the element is detached during the checks, the whole action is retried.
-
Scroll the element into view if needed.
-
Use [‘property: Page.mouse`] to double click in the center of the element, or the specified `position`.
-
Wait for initiated navigations to either succeed or fail, unless ‘noWaitAfter` option is set. Note that if the first click of the `dblclick()` triggers a navigation event, this method will reject.
When all steps combined have not finished during the specified ‘timeout`, this method rejects with a `TimeoutError`. Passing zero timeout disables this.
> NOTE ‘page.dblclick()` dispatches two `click` events and a single `dblclick` event.
Shortcut for main frame’s [‘method: Frame.dblclick`].
249 250 251 252 253 254 255 256 257 258 259 |
# File 'lib/playwright_api/page.rb', line 249 def dblclick( selector, button: nil, delay: nil, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, timeout: nil) raise NotImplementedError.new('dblclick is not implemented yet.') end |
#disabled?(selector, timeout: nil) ⇒ Boolean
Returns whether the element is disabled, the opposite of [enabled](./actionability.md#enabled).
646 647 648 |
# File 'lib/playwright_api/page.rb', line 646 def disabled?(selector, timeout: nil) raise NotImplementedError.new('disabled? is not implemented yet.') end |
#dispatch_event(selector, type, eventInit: nil, timeout: nil) ⇒ Object
The snippet below dispatches the ‘click` event on the element. Regardless of the visibility state of the elment, `click` is dispatched. This is equivalend to calling [element.click()](developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
“‘js await page.dispatchEvent(’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:
-
[DragEvent](developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
-
[FocusEvent](developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
-
[KeyboardEvent](developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
-
[MouseEvent](developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
-
[PointerEvent](developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
-
[TouchEvent](developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
-
[Event](developer.mozilla.org/en-US/docs/Web/API/Event/Event)
You can also specify ‘JSHandle` as the property value if you want live objects to be passed into the event:
“‘js // Note you can only create DataTransfer in Chromium and Firefox const dataTransfer = await page.evaluateHandle(() => new DataTransfer()); await page.dispatchEvent(’#source’, ‘dragstart’, { dataTransfer }); “‘
290 291 292 |
# File 'lib/playwright_api/page.rb', line 290 def dispatch_event(selector, type, eventInit: nil, timeout: nil) raise NotImplementedError.new('dispatch_event is not implemented yet.') end |
#editable?(selector, timeout: nil) ⇒ Boolean
Returns whether the element is [editable](./actionability.md#editable).
651 652 653 |
# File 'lib/playwright_api/page.rb', line 651 def editable?(selector, timeout: nil) raise NotImplementedError.new('editable? is not implemented yet.') end |
#emulate_media(params) ⇒ Object
“‘js await page.evaluate(() => matchMedia(’screen’).matches); // → true await page.evaluate(() => matchMedia(‘print’).matches); // → false
await page.emulateMedia({ media: ‘print’ }); await page.evaluate(() => matchMedia(‘screen’).matches); // → false await page.evaluate(() => matchMedia(‘print’).matches); // → true
await page.emulateMedia({}); await page.evaluate(() => matchMedia(‘screen’).matches); // → true await page.evaluate(() => matchMedia(‘print’).matches); // → false “‘
“‘js await page.emulateMedia({ colorScheme: ’dark’ }); await page.evaluate(() => matchMedia(‘(prefers-color-scheme: dark)’).matches); // → true await page.evaluate(() => matchMedia(‘(prefers-color-scheme: light)’).matches); // → false await page.evaluate(() => matchMedia(‘(prefers-color-scheme: no-preference)’).matches); // → false “‘
325 326 327 |
# File 'lib/playwright_api/page.rb', line 325 def emulate_media(params) raise NotImplementedError.new('emulate_media is not implemented yet.') end |
#enabled?(selector, timeout: nil) ⇒ Boolean
Returns whether the element is [enabled](./actionability.md#enabled).
656 657 658 |
# File 'lib/playwright_api/page.rb', line 656 def enabled?(selector, timeout: nil) raise NotImplementedError.new('enabled? is not implemented yet.') end |
#eval_on_selector(selector, pageFunction, arg: nil) ⇒ Object
The method finds an element matching the specified selector within the page and passes it as a first argument to ‘pageFunction`. If no elements match the selector, the method throws an error. Returns the value of `pageFunction`.
If ‘pageFunction` returns a [Promise], then [`method: Page.$eval`] would wait for the promise to resolve and return its value.
Examples:
“‘js const searchValue = await page.$eval(’#search’, el => el.value); const preloadHref = await page.$eval(‘link’, el => el.href); const html = await page.$eval(‘.main-container’, (e, suffix) => e.outerHTML + suffix, ‘hello’); “‘
Shortcut for main frame’s [‘method: Frame.$eval`].
102 103 104 |
# File 'lib/playwright_api/page.rb', line 102 def eval_on_selector(selector, pageFunction, arg: nil) raise NotImplementedError.new('eval_on_selector is not implemented yet.') end |
#eval_on_selector_all(selector, pageFunction, 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 ‘pageFunction`. Returns the result of `pageFunction` invocation.
If ‘pageFunction` returns a [Promise], then [`method: Page.$$eval`] would wait for the promise to resolve and return its value.
Examples:
“‘js const divsCounts = await page.$$eval(’div’, (divs, min) => divs.length >= min, 10); “‘
118 119 120 |
# File 'lib/playwright_api/page.rb', line 118 def eval_on_selector_all(selector, pageFunction, arg: nil) raise NotImplementedError.new('eval_on_selector_all is not implemented yet.') end |
#evaluate(pageFunction, arg: nil) ⇒ Object
Returns the value of the ‘pageFunction` invocation.
If the function passed to the ‘page.evaluate` returns a [Promise], then `page.evaluate` would wait for the promise to resolve and return its value.
If the function passed to the ‘page.evaluate` returns a non- value, then `page.evaluate` resolves to `undefined`. DevTools Protocol also supports transferring some additional values that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.
Passing argument to ‘pageFunction`:
“‘js const result = await page.evaluate(([x, y]) =>
return Promise.resolve(x * y);
, [7, 8]); console.log(result); // prints “56” “‘
A string can also be passed in instead of a function:
“‘js console.log(await page.evaluate(’1 + 2’)); // prints “3” const x = 10; console.log(await page.evaluate(‘1 + $x`)); // prints “11” “`
‘ElementHandle` instances can be passed as an argument to the `page.evaluate`:
“‘js const bodyHandle = await page.$(’body’); const html = await page.evaluate(([body, suffix]) => body.innerHTML + suffix, [bodyHandle, ‘hello’]); await bodyHandle.dispose(); “‘
Shortcut for main frame’s [‘method: Frame.evaluate`].
367 368 369 |
# File 'lib/playwright_api/page.rb', line 367 def evaluate(pageFunction, arg: nil) raise NotImplementedError.new('evaluate is not implemented yet.') end |
#evaluate_handle(pageFunction, arg: nil) ⇒ Object
Returns the value of the ‘pageFunction` invocation as in-page object (JSHandle).
The only difference between ‘page.evaluate` and `page.evaluateHandle` is that `page.evaluateHandle` returns in-page object (JSHandle).
If the function passed to the ‘page.evaluateHandle` returns a [Promise], then `page.evaluateHandle` would wait for the promise to resolve and return its value.
A string can also be passed in instead of a function:
“‘js const aHandle = await page.evaluateHandle(’document’); // Handle for the ‘document’ “‘
‘JSHandle` instances can be passed as an argument to the `page.evaluateHandle`:
“‘js const aHandle = await page.evaluateHandle(() => document.body); const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle); console.log(await resultHandle.jsonValue()); await resultHandle.dispose(); “`
395 396 397 |
# File 'lib/playwright_api/page.rb', line 395 def evaluate_handle(pageFunction, arg: nil) raise NotImplementedError.new('evaluate_handle is not implemented yet.') end |
#expose_binding(name, callback, handle: nil) ⇒ 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 ‘page.exposeBinding` survive navigations.
An example of exposing page URL to all frames in a page:
“‘js const { webkit } = require(’playwright’); // Or ‘chromium’ or ‘firefox’.
(async () => {
const browser = await webkit.launch({ headless: false });
const context = await browser.newContext();
const page = await context.newPage();
await page.exposeBinding('pageURL', ({ page }) => page.url());
await page.setContent(`
<script>
async function onClick() {
document.querySelector('div').textContent = await window.pageURL();
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
`);
await page.click('button');
})(); “‘
An example of passing an element handle:
“‘js await page.exposeBinding(’clicked’, async (source, element) =>
console.log(await element.textContent());
, { handle: true }); await page.setContent(‘
<script>
document.addEventListener('click', event => window.clicked(event.target));
</script>
<div>Click me</div>
<div>Or click me</div>
‘); “`
449 450 451 |
# File 'lib/playwright_api/page.rb', line 449 def expose_binding(name, callback, handle: nil) raise NotImplementedError.new('expose_binding is not implemented yet.') 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 ‘page.exposeFunction` survive navigations.
An example of adding an ‘md5` function to the page:
“‘js const { webkit } = require(’playwright’); // Or ‘chromium’ or ‘firefox’. const crypto = require(‘crypto’);
(async () => {
const browser = await webkit.launch({ headless: false });
const page = await browser.newPage();
await page.exposeFunction('md5', text => crypto.createHash('md5').update(text).digest('hex'));
await page.setContent(`
<script>
async function onClick() {
document.querySelector('div').textContent = await window.md5('PLAYWRIGHT');
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
`);
await page.click('button');
})(); “‘
An example of adding a ‘window.readfile` function to the page:
“‘js const { chromium } = require(’playwright’); // Or ‘firefox’ or ‘webkit’. const fs = require(‘fs’);
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
page.on('console', msg => console.log(msg.text()));
await page.exposeFunction('readfile', async filePath => {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf8', (err, text) => {
if (err)
reject(err);
else
resolve(text);
});
});
});
await page.evaluate(async () => {
// use window.readfile to read contents of a file
const content = await window.readfile('/etc/hosts');
console.log(content);
});
await browser.close();
})(); “‘
515 516 517 |
# File 'lib/playwright_api/page.rb', line 515 def expose_function(name, callback) raise NotImplementedError.new('expose_function is not implemented yet.') end |
#fill(selector, value, noWaitAfter: nil, timeout: nil) ⇒ Object
This method waits for an element matching ‘selector`, waits for [actionability](./actionability.md) checks, focuses the element, fills it and triggers an `input` event after filling. If the element matching `selector` is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an error. Note that you can pass an empty string to clear the input field.
To send fine-grained keyboard events, use [‘method: Page.type`].
Shortcut for main frame’s [‘method: Frame.fill`]
527 528 529 |
# File 'lib/playwright_api/page.rb', line 527 def fill(selector, value, noWaitAfter: nil, timeout: nil) raise NotImplementedError.new('fill is not implemented yet.') end |
#focus(selector, timeout: nil) ⇒ Object
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.
Shortcut for main frame’s [‘method: Frame.focus`].
535 536 537 |
# File 'lib/playwright_api/page.rb', line 535 def focus(selector, timeout: nil) raise NotImplementedError.new('focus is not implemented yet.') end |
#frame(frameSelector) ⇒ Object
Returns frame matching the specified criteria. Either ‘name` or `url` must be specified.
“‘js const frame = page.frame(’frame-name’); “‘
“‘js const frame = page.frame({ url: /.domain./ }); “`
550 551 552 |
# File 'lib/playwright_api/page.rb', line 550 def frame(frameSelector) raise NotImplementedError.new('frame is not implemented yet.') end |
#frames ⇒ Object
An array of all frames attached to the page.
555 556 557 |
# File 'lib/playwright_api/page.rb', line 555 def frames raise NotImplementedError.new('frames is not implemented yet.') end |
#get_attribute(selector, name, timeout: nil) ⇒ Object
Returns element attribute value.
560 561 562 |
# File 'lib/playwright_api/page.rb', line 560 def get_attribute(selector, name, timeout: nil) raise NotImplementedError.new('get_attribute is not implemented yet.') end |
#go_back(timeout: nil, waitUntil: nil) ⇒ Object
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go back, returns ‘null`.
Navigate to the previous page in history.
568 569 570 |
# File 'lib/playwright_api/page.rb', line 568 def go_back(timeout: nil, waitUntil: nil) raise NotImplementedError.new('go_back is not implemented yet.') end |
#go_forward(timeout: nil, waitUntil: nil) ⇒ Object
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go forward, returns ‘null`.
Navigate to the next page in history.
576 577 578 |
# File 'lib/playwright_api/page.rb', line 576 def go_forward(timeout: nil, waitUntil: nil) raise NotImplementedError.new('go_forward is not implemented yet.') end |
#goto(url, referer: nil, timeout: nil, waitUntil: nil) ⇒ Object
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
‘page.goto` 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.
‘page.goto` 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 ‘page.goto` 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](bugs.chromium.org/p/chromium/issues/detail?id=761295).
Shortcut for main frame’s [‘method: Frame.goto`]
600 601 602 |
# File 'lib/playwright_api/page.rb', line 600 def goto(url, referer: nil, timeout: nil, waitUntil: nil) wrap_channel_owner(@channel_owner.goto(url, referer: referer, timeout: timeout, waitUntil: waitUntil)) end |
#hidden?(selector, timeout: nil) ⇒ Boolean
Returns whether the element is hidden, the opposite of [visible](./actionability.md#visible).
661 662 663 |
# File 'lib/playwright_api/page.rb', line 661 def hidden?(selector, timeout: nil) raise NotImplementedError.new('hidden? is not implemented yet.') end |
#hover(selector, force: nil, modifiers: nil, position: nil, timeout: nil) ⇒ Object
This method hovers over an element matching ‘selector` by performing the following steps:
-
Find an element match matching ‘selector`. If there is none, wait until a matching element is attached to the DOM.
-
Wait for [actionability](./actionability.md) checks on the matched element, unless ‘force` option is set. If the element is detached during the checks, the whole action is retried.
-
Scroll the element into view if needed.
-
Use [‘property: Page.mouse`] to hover over the center of the element, or the specified `position`.
-
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 rejects with a `TimeoutError`. Passing zero timeout disables this.
Shortcut for main frame’s [‘method: Frame.hover`].
616 617 618 619 620 621 622 623 |
# File 'lib/playwright_api/page.rb', line 616 def hover( selector, force: nil, modifiers: nil, position: nil, timeout: nil) raise NotImplementedError.new('hover is not implemented yet.') end |
#inner_html(selector, timeout: nil) ⇒ Object
Returns ‘element.innerHTML`.
626 627 628 |
# File 'lib/playwright_api/page.rb', line 626 def inner_html(selector, timeout: nil) raise NotImplementedError.new('inner_html is not implemented yet.') end |
#inner_text(selector, timeout: nil) ⇒ Object
Returns ‘element.innerText`.
631 632 633 |
# File 'lib/playwright_api/page.rb', line 631 def inner_text(selector, timeout: nil) raise NotImplementedError.new('inner_text is not implemented yet.') end |
#keyboard ⇒ Object
property
58 59 60 |
# File 'lib/playwright_api/page.rb', line 58 def keyboard # property wrap_channel_owner(@channel_owner.keyboard) end |
#main_frame ⇒ Object
The page’s main frame. Page is guaranteed to have a main frame which persists during navigations.
671 672 673 |
# File 'lib/playwright_api/page.rb', line 671 def main_frame wrap_channel_owner(@channel_owner.main_frame) end |
#mouse ⇒ Object
property
62 63 64 |
# File 'lib/playwright_api/page.rb', line 62 def mouse # property wrap_channel_owner(@channel_owner.mouse) end |
#opener ⇒ Object
Returns the opener for popup pages and ‘null` for others. If the opener has been closed already the returns `null`.
676 677 678 |
# File 'lib/playwright_api/page.rb', line 676 def opener raise NotImplementedError.new('opener is not implemented yet.') end |
#owned_context=(req) ⇒ Object
1197 1198 1199 |
# File 'lib/playwright_api/page.rb', line 1197 def owned_context=(req) wrap_channel_owner(@channel_owner.owned_context=(req)) end |
#pdf(displayHeaderFooter: nil, footerTemplate: nil, format: nil, headerTemplate: nil, height: nil, landscape: nil, margin: nil, pageRanges: nil, path: nil, preferCSSPageSize: nil, printBackground: nil, scale: nil, width: nil) ⇒ Object
Returns the PDF buffer.
> NOTE Generating a pdf is currently only supported in Chromium headless.
‘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`](developer.mozilla.org/en-US/docs/Web/CSS/-webkit-print-color-adjust) property to force rendering of exact colors.
“‘js // Generates a PDF with ’screen’ media type. await page.emulateMedia(‘screen’); await page.pdf(‘page.pdf’); “‘
The ‘width`, `height`, and `margin` options accept values labeled with units. Unlabeled values are treated as pixels.
A few examples:
-
‘page.pdf(100)` - prints with width set to 100 pixels
-
‘page.pdf(’100px’)‘ - prints with width set to 100 pixels
-
‘page.pdf(’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.
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 |
# File 'lib/playwright_api/page.rb', line 727 def pdf( displayHeaderFooter: nil, footerTemplate: nil, format: nil, headerTemplate: nil, height: nil, landscape: nil, margin: nil, pageRanges: nil, path: nil, preferCSSPageSize: nil, printBackground: nil, scale: nil, width: nil) raise NotImplementedError.new('pdf is not implemented yet.') end |
#press(selector, key, delay: nil, noWaitAfter: nil, timeout: nil) ⇒ Object
Focuses the element, and then uses [‘method: Keyboard.down`] and [`method: Keyboard.up`].
‘key` can specify the intended [keyboardEvent.key](developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character to generate the text for. A superset of the `key` values can be found [here](developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). 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`.
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”` or `key: “Control+Shift+T”` are supported as well. When speficied with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
“‘js const page = await browser.newPage(); await page.goto(’keycode.info’); await page.press(‘body’, ‘A’); await page.screenshot({ path: ‘A.png’ }); await page.press(‘body’, ‘ArrowLeft’); await page.screenshot({ path: ‘ArrowLeft.png’ }); await page.press(‘body’, ‘Shift+O’); await page.screenshot({ path: ‘O.png’ }); await browser.close(); “‘
775 776 777 778 779 780 781 782 |
# File 'lib/playwright_api/page.rb', line 775 def press( selector, key, delay: nil, noWaitAfter: nil, timeout: nil) raise NotImplementedError.new('press is not implemented yet.') end |
#query_selector(selector) ⇒ Object
The method finds an element matching the specified selector within the page. If no elements match the selector, the return value resolves to ‘null`.
Shortcut for main frame’s [‘method: Frame.$`].
74 75 76 |
# File 'lib/playwright_api/page.rb', line 74 def query_selector(selector) raise NotImplementedError.new('query_selector is not implemented yet.') end |
#query_selector_all(selector) ⇒ Object
The method finds all elements matching the specified selector within the page. If no elements match the selector, the return value resolves to ‘[]`.
Shortcut for main frame’s [‘method: Frame.$$`].
82 83 84 |
# File 'lib/playwright_api/page.rb', line 82 def query_selector_all(selector) raise NotImplementedError.new('query_selector_all is not implemented yet.') end |
#reload(timeout: nil, waitUntil: nil) ⇒ Object
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
786 787 788 |
# File 'lib/playwright_api/page.rb', line 786 def reload(timeout: nil, waitUntil: nil) raise NotImplementedError.new('reload is not implemented yet.') end |
#route(url, handler) ⇒ 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.
An example of a naïve handler that aborts all image requests:
“‘js const page = await browser.newPage(); await page.route(’*/.png,jpg,jpeg‘, route => route.abort()); await page.goto(’example.com’); await browser.close(); “‘
or the same snippet using a regex pattern instead:
“‘js const page = await browser.newPage(); await page.route(/(.png$)|(.jpg$)/, route => route.abort()); await page.goto(’example.com’); await browser.close(); “‘
Page routes take precedence over browser context routes (set up with [‘method: BrowserContext.route`]) when request matches both handlers.
> NOTE Enabling routing disables http cache.
820 821 822 |
# File 'lib/playwright_api/page.rb', line 820 def route(url, handler) raise NotImplementedError.new('route is not implemented yet.') end |
#screenshot(clip: nil, fullPage: nil, omitBackground: nil, path: nil, quality: nil, timeout: nil, type: nil) ⇒ Object
Returns the buffer with the captured screenshot.
> NOTE Screenshots take at least 1/6 second on Chromium OS X and Chromium Windows. See crbug.com/741689 for discussion.
828 829 830 831 832 833 834 835 836 837 |
# File 'lib/playwright_api/page.rb', line 828 def screenshot( clip: nil, fullPage: nil, omitBackground: nil, path: nil, quality: nil, timeout: nil, type: nil) wrap_channel_owner(@channel_owner.screenshot(clip: clip, fullPage: fullPage, omitBackground: omitBackground, path: path, quality: quality, timeout: timeout, type: type)) end |
#select_option(selector, values, noWaitAfter: nil, timeout: nil) ⇒ Object
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. If there’s no ‘<select>` element matching `selector`, the method throws an error.
“‘js // single selection matching the value page.selectOption(’select#colors’, ‘blue’);
// single selection matching both the value and the label page.selectOption(‘select#colors’, { label: ‘Blue’ });
// multiple selection page.selectOption(‘select#colors’, [‘red’, ‘green’, ‘blue’]);
“‘
Shortcut for main frame’s [‘method: Frame.selectOption`]
858 859 860 |
# File 'lib/playwright_api/page.rb', line 858 def select_option(selector, values, noWaitAfter: nil, timeout: nil) raise NotImplementedError.new('select_option is not implemented yet.') end |
#set_content(html, timeout: nil, waitUntil: nil) ⇒ Object
862 863 864 |
# File 'lib/playwright_api/page.rb', line 862 def set_content(html, timeout: nil, waitUntil: nil) raise NotImplementedError.new('set_content is not implemented yet.') end |
#set_default_navigation_timeout(timeout) ⇒ Object Also known as:
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`
> NOTE [‘method: Page.setDefaultNavigationTimeout`] takes priority over [`method: Page.setDefaultTimeout`],
- ‘method: BrowserContext.setDefaultTimeout`
-
and [‘method: BrowserContext.setDefaultNavigationTimeout`].
876 877 878 |
# File 'lib/playwright_api/page.rb', line 876 def (timeout) raise NotImplementedError.new('set_default_navigation_timeout is not implemented yet.') end |
#set_default_timeout(timeout) ⇒ Object Also known as: default_timeout=
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`].
884 885 886 |
# File 'lib/playwright_api/page.rb', line 884 def set_default_timeout(timeout) raise NotImplementedError.new('set_default_timeout is not implemented yet.') end |
#set_extra_http_headers(headers) ⇒ Object Also known as: extra_http_headers=
The extra HTTP headers will be sent with every request the page initiates.
> NOTE page.setExtraHTTPHeaders does not guarantee the order of headers in the outgoing requests.
892 893 894 |
# File 'lib/playwright_api/page.rb', line 892 def set_extra_http_headers(headers) raise NotImplementedError.new('set_extra_http_headers is not implemented yet.') end |
#set_input_files(selector, files, noWaitAfter: nil, timeout: nil) ⇒ Object
This method expects ‘selector` to point to an [input element](developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
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 the current working directory. For empty array, clears the selected files.
902 903 904 |
# File 'lib/playwright_api/page.rb', line 902 def set_input_files(selector, files, noWaitAfter: nil, timeout: nil) raise NotImplementedError.new('set_input_files is not implemented yet.') end |
#set_viewport_size(viewportSize) ⇒ Object Also known as: viewport_size=
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.
‘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.
“‘js const page = await browser.newPage(); await page.setViewportSize(
width: 640,
height: 480,
); await page.goto(‘example.com’); “‘
921 922 923 |
# File 'lib/playwright_api/page.rb', line 921 def () wrap_channel_owner(@channel_owner.()) end |
#tap_point(selector, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, timeout: nil) ⇒ Object
This method taps an element matching ‘selector` by performing the following steps:
-
Find an element match matching ‘selector`. If there is none, wait until a matching element is attached to the DOM.
-
Wait for [actionability](./actionability.md) checks on the matched element, unless ‘force` option is set. If the element is detached during the checks, the whole action is retried.
-
Scroll the element into view if needed.
-
Use [‘property: Page.touchscreen`] to tap the center of the element, or the specified `position`.
-
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 rejects with a `TimeoutError`. Passing zero timeout disables this.
> NOTE ‘page.tap()` requires that the `hasTouch` option of the browser context be set to true.
Shortcut for main frame’s [‘method: Frame.tap`].
940 941 942 943 944 945 946 947 948 |
# File 'lib/playwright_api/page.rb', line 940 def tap_point( selector, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, timeout: nil) raise NotImplementedError.new('tap_point is not implemented yet.') end |
#text_content(selector, timeout: nil) ⇒ Object
Returns ‘element.textContent`.
951 952 953 |
# File 'lib/playwright_api/page.rb', line 951 def text_content(selector, timeout: nil) raise NotImplementedError.new('text_content is not implemented yet.') end |
#title ⇒ Object
Returns the page’s title. Shortcut for main frame’s [‘method: Frame.title`].
956 957 958 |
# File 'lib/playwright_api/page.rb', line 956 def title raise NotImplementedError.new('title is not implemented yet.') end |
#touchscreen ⇒ Object
property
66 67 68 |
# File 'lib/playwright_api/page.rb', line 66 def touchscreen # property wrap_channel_owner(@channel_owner.touchscreen) end |
#type_text(selector, text, delay: nil, noWaitAfter: nil, timeout: nil) ⇒ Object
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`].
“‘js await page.type(’#mytextarea’, ‘Hello’); // Types instantly await page.type(‘#mytextarea’, ‘World’, 100); // Types slower, like a user “‘
Shortcut for main frame’s [‘method: Frame.type`].
972 973 974 975 976 977 978 979 |
# File 'lib/playwright_api/page.rb', line 972 def type_text( selector, text, delay: nil, noWaitAfter: nil, timeout: nil) raise NotImplementedError.new('type_text is not implemented yet.') end |
#uncheck(selector, force: nil, noWaitAfter: nil, timeout: nil) ⇒ Object
This method unchecks an element matching ‘selector` by performing the following steps:
-
Find an element match matching ‘selector`. If there is none, wait until a matching element is attached to the DOM.
-
Ensure that matched element is a checkbox or a radio input. If not, this method rejects. If the element is already unchecked, this method returns immediately.
-
Wait for [actionability](./actionability.md) checks on the matched element, unless ‘force` option is set. If the element is detached during the checks, the whole action is retried.
-
Scroll the element into view if needed.
-
Use [‘property: Page.mouse`] to click in the center of the element.
-
Wait for initiated navigations to either succeed or fail, unless ‘noWaitAfter` option is set.
-
Ensure that the element is now unchecked. If not, this method rejects.
When all steps combined have not finished during the specified ‘timeout`, this method rejects with a `TimeoutError`. Passing zero timeout disables this.
Shortcut for main frame’s [‘method: Frame.uncheck`].
996 997 998 |
# File 'lib/playwright_api/page.rb', line 996 def uncheck(selector, force: nil, noWaitAfter: nil, timeout: nil) raise NotImplementedError.new('uncheck is not implemented yet.') end |
#unroute(url, handler: nil) ⇒ Object
Removes a route created with [‘method: Page.route`]. When `handler` is not specified, removes all routes for the `url`.
1001 1002 1003 |
# File 'lib/playwright_api/page.rb', line 1001 def unroute(url, handler: nil) raise NotImplementedError.new('unroute is not implemented yet.') end |
#url ⇒ Object
Shortcut for main frame’s [‘method: Frame.url`].
1006 1007 1008 |
# File 'lib/playwright_api/page.rb', line 1006 def url raise NotImplementedError.new('url is not implemented yet.') end |
#video ⇒ Object
Video object associated with this page.
1011 1012 1013 |
# File 'lib/playwright_api/page.rb', line 1011 def video raise NotImplementedError.new('video is not implemented yet.') end |
#viewport_size ⇒ Object
1015 1016 1017 |
# File 'lib/playwright_api/page.rb', line 1015 def wrap_channel_owner(@channel_owner.) end |
#visible?(selector, timeout: nil) ⇒ Boolean
Returns whether the element is [visible](./actionability.md#visible).
666 667 668 |
# File 'lib/playwright_api/page.rb', line 666 def visible?(selector, timeout: nil) raise NotImplementedError.new('visible? is not implemented yet.') end |
#wait_for_event(event, optionsOrPredicate: nil) ⇒ Object
Returns the event data value.
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.
1023 1024 1025 |
# File 'lib/playwright_api/page.rb', line 1023 def wait_for_event(event, optionsOrPredicate: nil) raise NotImplementedError.new('wait_for_event is not implemented yet.') end |
#wait_for_function(pageFunction, arg: nil, polling: nil, timeout: nil) ⇒ Object
Returns when the ‘pageFunction` returns a truthy value. It resolves to a JSHandle of the truthy value.
The ‘waitForFunction` can be used to observe viewport size change:
“‘js const { webkit } = require(’playwright’); // Or ‘chromium’ or ‘firefox’.
(async () =>
const browser = await webkit.launch();
const page = await browser.newPage();
const watchDog = page.waitForFunction('window.innerWidth < 100');
await page.setViewportSize({width: 50, height: 50);
await watchDog;
await browser.close();
})(); “‘
To pass an argument to the predicate of ‘page.waitForFunction` function:
“‘js const selector = ’.foo’; await page.waitForFunction(selector => !!document.querySelector(selector), selector); “‘
Shortcut for main frame’s [‘method: Frame.waitForFunction`].
1054 1055 1056 |
# File 'lib/playwright_api/page.rb', line 1054 def wait_for_function(pageFunction, arg: nil, polling: nil, timeout: nil) raise NotImplementedError.new('wait_for_function is not implemented yet.') end |
#wait_for_load_state(state: nil, timeout: nil) ⇒ Object
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.
“‘js await page.click(’button’); // Click triggers navigation. await page.waitForLoadState(); // The promise resolves after ‘load’ event. “‘
“‘js const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.click('button'), // Click triggers a popup.
]) await popup.waitForLoadState(‘domcontentloaded’); // The promise resolves after ‘domcontentloaded’ event. console.log(await popup.title()); // Popup is ready to use. “‘
Shortcut for main frame’s [‘method: Frame.waitForLoadState`].
1080 1081 1082 |
# File 'lib/playwright_api/page.rb', line 1080 def wait_for_load_state(state: nil, timeout: nil) raise NotImplementedError.new('wait_for_load_state is not implemented yet.') end |
#wait_for_navigation(timeout: nil, url: nil, waitUntil: nil) ⇒ Object
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`.
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:
“‘js const [response] = await Promise.all([
page.waitForNavigation(), // The promise resolves after navigation has finished
page.click('a.delayed-navigation'), // Clicking the link will indirectly cause a navigation
]); “‘
NOTE Usage of the [History API](developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL is considered a navigation.
Shortcut for main frame’s [‘method: Frame.waitForNavigation`].
1104 1105 1106 |
# File 'lib/playwright_api/page.rb', line 1104 def (timeout: nil, url: nil, waitUntil: nil) raise NotImplementedError.new('wait_for_navigation is not implemented yet.') end |
#wait_for_request(urlOrPredicate, timeout: nil) ⇒ Object
Waits for the matching request and returns it.
“‘js const firstRequest = await page.waitForRequest(’example.com/resource’); const finalRequest = await page.waitForRequest(request => request.url() === ‘example.com’ && request.method() === ‘GET’); return firstRequest.url(); “‘
“‘js await page.waitForRequest(request => request.url().searchParams.get(’foo’) === ‘bar’ && request.url().searchParams.get(‘foo2’) === ‘bar2’); “‘
1121 1122 1123 |
# File 'lib/playwright_api/page.rb', line 1121 def wait_for_request(urlOrPredicate, timeout: nil) raise NotImplementedError.new('wait_for_request is not implemented yet.') end |
#wait_for_response(urlOrPredicate, timeout: nil) ⇒ Object
Returns the matched response.
“‘js const firstResponse = await page.waitForResponse(’example.com/resource’); const finalResponse = await page.waitForResponse(response => response.url() === ‘example.com’ && response.status() === 200); return finalResponse.ok(); “‘
1133 1134 1135 |
# File 'lib/playwright_api/page.rb', line 1133 def wait_for_response(urlOrPredicate, timeout: nil) raise NotImplementedError.new('wait_for_response is not implemented yet.') end |
#wait_for_selector(selector, state: nil, timeout: nil) ⇒ Object
Returns when element specified by selector satisfies ‘state` option. Returns `null` if waiting for `hidden` or `detached`.
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.
This method works across navigations:
“‘js const { chromium } = require(’playwright’); // Or ‘firefox’ or ‘webkit’.
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
let currentURL;
page
.waitForSelector('img')
.then(() => console.log('First URL with image: ' + currentURL));
for (currentURL of ['https://example.com', 'https://google.com', 'https://bbc.com']) {
await page.goto(currentURL);
}
await browser.close();
})(); “‘
1163 1164 1165 |
# File 'lib/playwright_api/page.rb', line 1163 def wait_for_selector(selector, state: nil, timeout: nil) raise NotImplementedError.new('wait_for_selector is not implemented yet.') end |
#wait_for_timeout(timeout) ⇒ Object
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.
“‘js // wait for 1 second await page.waitForTimeout(1000); “`
Shortcut for main frame’s [‘method: Frame.waitForTimeout`].
1179 1180 1181 |
# File 'lib/playwright_api/page.rb', line 1179 def wait_for_timeout(timeout) raise NotImplementedError.new('wait_for_timeout is not implemented yet.') end |
#workers ⇒ Object
This method returns all of the dedicated [WebWorkers](developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) associated with the page.
> NOTE This does not contain ServiceWorkers
1187 1188 1189 |
# File 'lib/playwright_api/page.rb', line 1187 def workers raise NotImplementedError.new('workers is not implemented yet.') end |