Frame

Struct Frame 

Source
pub struct Frame {
    inner: Weak<Frame>,
}
Expand description

At every point of time, page exposes its current frame tree via the [method: Page.mainFrame] and [method: Frame.childFrames] methods.

Frame object’s lifecycle is controlled by three events, dispatched on the page object:

  • [event: Page.frameAttached] - fired when the frame gets attached to the page. A Frame can be attached to the page only once.
  • [event: Page.frameNavigated] - fired when the frame commits navigation to a different URL.
  • [event: Page.frameDetached] - fired when the frame gets detached from the page. A Frame can be detached from the page only once.

An example of dumping frame tree:

const { firefox } = require('playwright');  // Or 'chromium' or 'webkit'.

(async () => {
 const browser = await firefox.launch();
 const page = await browser.newPage();
 await page.goto('https://www.google.com/chrome/browser/canary.html');
 dumpFrameTree(page.mainFrame(), '');
 await browser.close();

 function dumpFrameTree(frame, indent) {
   console.log(indent + frame.url());
   for (const child of frame.childFrames()) {
     dumpFrameTree(child, indent + '  ');
   }
 }
})();

Fields§

§inner: Weak<Frame>

Implementations§

Source§

impl Frame

Source

pub(crate) fn new(inner: Weak<Impl>) -> Self

Source

pub fn url(&self) -> Result<String, Error>

Source

pub fn name(&self) -> Result<String, Error>

Returns frame’s name attribute as specified in the tag.

If the name is empty, returns the id attribute instead.

NOTE: This value is calculated once when the frame is created, and will not update if the attribute is changed later.

Source

pub fn page(&self) -> Result<Option<Page>, Error>

Source

pub fn parent_frame(&self) -> Result<Option<Frame>, Error>

Parent frame, if any. Detached frames and main frames return null.

Source

pub fn child_frames(&self) -> Result<Vec<Frame>, Error>

Source

pub fn goto_builder<'a>(&self, url: &'a str) -> GotoBuilder<'a, '_>

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

frame.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.

frame.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: frame.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.

Source

pub fn click_builder<'a>(&self, selector: &'a str) -> ClickBuilder<'a>

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.

Source

pub fn dblclick_builder<'a>(&self, selector: &'a str) -> DblClickBuilder<'a>

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.
  5. 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 throw.

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

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

Source

pub fn tap_builder<'a>(&self, selector: &'a str) -> TapBuilder<'a>

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.
  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.

NOTE: frame.tap() requires that the hasTouch option of the browser context be set to true.

Source

pub fn fill_builder<'a, 'b>( &self, selector: &'a str, value: &'b str, ) -> FillBuilder<'a, 'b>

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 Frame::type_builder.

Source

pub async fn focus( &self, selector: &str, timeout: Option<f64>, ) -> Result<(), Arc<Error>>

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.

Source

pub async fn text_content( &self, selector: &str, timeout: Option<f64>, ) -> Result<Option<String>, Arc<Error>>

Returns element.textContent.

Source

pub async fn inner_text( &self, selector: &str, timeout: Option<f64>, ) -> Result<String, Arc<Error>>

Returns element.innerText.

Source

pub async fn inner_html( &self, selector: &str, timeout: Option<f64>, ) -> Result<String, Arc<Error>>

Returns element.innerHTML.

Source

pub async fn get_attribute( &self, selector: &str, name: &str, timeout: Option<f64>, ) -> Result<Option<String>, Arc<Error>>

Returns element attribute value.

Source

pub async fn query_selector( &self, selector: &str, ) -> Result<Option<ElementHandle>, Arc<Error>>

Source

pub async fn query_selector_all( &self, selector: &str, ) -> Result<Vec<ElementHandle>, Arc<Error>>

Source

pub async fn frame_element(&self) -> Result<ElementHandle, Arc<Error>>

Returns the frame or iframe element handle which corresponds to this frame.

This is an inverse of [method: ElementHandle.contentFrame]. Note that returned handle actually belongs to the parent frame.

This method throws an error if the frame has been detached before frameElement() returns.

const frameElement = await frame.frameElement();
const contentFrame = await frameElement.contentFrame();
console.log(frame === contentFrame);  // -> true
Source

pub fn wait_for_selector_builder<'a>( &self, selector: &'a str, ) -> WaitForSelectorBuilder<'a>

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:

const { chromium } = require('playwright');  // Or 'firefox' or 'webkit'.

(async () => {
 const browser = await chromium.launch();
 const page = await browser.newPage();
 for (let currentURL of ['https://google.com', 'https://bbc.com']) {
   await page.goto(currentURL);
   const element = await page.mainFrame().waitForSelector('img');
   console.log('Loaded image: ' + await element.getAttribute('src'));
 }
 await browser.close();
})();
Source

pub async fn title(&self) -> Result<String, Arc<Error>>

Source

pub fn type_builder<'a, 'b>( &self, selector: &'a str, text: &'b str, ) -> TypeBuilder<'a, 'b>

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

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

await frame.type('#mytextarea', 'Hello'); // Types instantly
await frame.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user
Source

pub fn press_builder<'a, 'b>( &self, selector: &'a str, key: &'b str, ) -> PressBuilder<'a, 'b>

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.

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 specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.

Source

pub fn hover_builder<'a>(&self, selector: &'a str) -> HoverBuilder<'a>

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.
  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.

Source

pub async fn is_checked( &self, selector: &str, timeout: Option<f64>, ) -> Result<bool, Arc<Error>>

Source

pub async fn is_disabled( &self, selector: &str, timeout: Option<f64>, ) -> Result<bool, Arc<Error>>

Source

pub async fn is_editable( &self, selector: &str, timeout: Option<f64>, ) -> Result<bool, Arc<Error>>

Source

pub async fn is_enabled( &self, selector: &str, timeout: Option<f64>, ) -> Result<bool, Arc<Error>>

Source

pub async fn is_hidden( &self, selector: &str, timeout: Option<f64>, ) -> Result<bool, Arc<Error>>

Source

pub async fn is_visible( &self, selector: &str, timeout: Option<f64>, ) -> Result<bool, Arc<Error>>

Source

pub async fn content<'a>(&self) -> Result<String, Arc<Error>>

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

Source

pub fn set_content_builder<'a>(&self, html: &'a str) -> SetContentBuilder<'a>

Source

pub fn check_builder<'a>(&self, selector: &'a str) -> CheckBuilder<'a>

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. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.
  7. 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.

Source

pub fn uncheck_builder<'a>(&self, selector: &'a str) -> UncheckBuilder<'a>

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 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. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.
  7. 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.

Source

pub async fn wait_for_timeout(&self, timeout: f64)

Source

pub async fn add_style_tag( &self, content: &str, url: Option<&str>, ) -> Result<ElementHandle, Arc<Error>>

Returns the added tag when the stylesheet’s onload fires or when the CSS content was injected into frame.

Adds a <link rel="stylesheet"> tag into the page with the desired url or a <style type="text/css"> tag with the content.

Source

pub fn add_script_tag_builder<'a>( &self, content: &'a str, ) -> AddScriptTagBuilder<'a, '_, '_>

Returns the added tag when the script’s onload fires or when the script content was injected into frame.

Adds a <script> tag into the page with the desired url or content.

Source

pub async fn evaluate_element_handle<T>( &self, expression: &str, args: Option<T>, ) -> Result<ElementHandle, Arc<Error>>
where T: Serialize,

Source

pub async fn evaluate_js_handle<T>( &self, expression: &str, arg: Option<T>, ) -> Result<JsHandle, Arc<Error>>
where T: Serialize,

Returns the return value of expression as a JSHandle.

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

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

const aWindowHandle = await frame.evaluateHandle(() => Promise.resolve(window));
aWindowHandle; // Handle for the window object.

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

const aHandle = await frame.evaluateHandle('document'); // Handle for the 'document'.

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

const aHandle = await frame.evaluateHandle(() => document.body);
const resultHandle = await frame.evaluateHandle(([body, suffix]) => body.innerHTML + suffix, [aHandle, 'hello']);
console.log(await resultHandle.jsonValue());
await resultHandle.dispose();
Source

pub async fn eval<U>(&self, expression: &str) -> Result<U, Arc<Error>>

Source

pub async fn evaluate<T, U>( &self, expression: &str, arg: T, ) -> Result<U, Arc<Error>>

Returns the return value of expression.

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

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

const result = await frame.evaluate(([x, y]) => {
 return Promise.resolve(x * y);
}, [7, 8]);
console.log(result); // prints "56"

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

const bodyHandle = await frame.$('body');
const html = await frame.evaluate(([body, suffix]) => body.innerHTML + suffix, [bodyHandle, 'hello']);
await bodyHandle.dispose();
Source

pub async fn evaluate_on_selector<T, U>( &self, selector: &str, expression: &str, arg: Option<T>, ) -> Result<U, Arc<Error>>

Returns the return value of expression.

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

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

Examples:

const searchValue = await frame.$eval('#search', el => el.value);
const preloadHref = await frame.$eval('link[rel=preload]', el => el.href);
const html = await frame.$eval('.main-container', (e, suffix) => e.outerHTML + suffix, 'hello');
Source

pub async fn evaluate_on_selector_all<T, U>( &self, selector: &str, expression: &str, arg: Option<T>, ) -> Result<U, Arc<Error>>

Returns the return value of expression.

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

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

Examples:

const divsCounts = await frame.$$eval('div', (divs, min) => divs.length >= min, 10);
Source

pub async fn dispatch_event<T>( &self, selector: &str, type: &str, event_init: Option<T>, ) -> Result<(), Arc<Error>>
where T: Serialize,

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().

await frame.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:

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

const dataTransfer = await frame.evaluateHandle(() => new DataTransfer());
await frame.dispatchEvent('#source', 'dragstart', { dataTransfer });
Source

pub fn select_option_builder<'a>( &self, selector: &'a str, ) -> SelectOptionBuilder<'a>

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.

frame.selectOption('select#colors', 'blue');
frame.selectOption('select#colors', { label: 'Blue' });
frame.selectOption('select#colors', 'red', 'green', 'blue');
Source

pub fn set_input_files_builder<'a>( &self, selector: &'a str, file: File, ) -> SetInputFilesBuilder<'a>

This method expects selector to point to an input element.

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.

Source

pub fn wait_for_function_builder<'a>( &self, expression: &'a str, ) -> WaitForFunctionBuilder<'a>

Returns when the expression returns a truthy value, returns that value.

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

const { firefox } = require('playwright');  // Or 'chromium' or 'webkit'.

(async () => {
 const browser = await firefox.launch();
 const page = await browser.newPage();
 const watchDog = page.mainFrame().waitForFunction('window.innerWidth < 100');
 page.setViewportSize({width: 50, height: 50});
 await watchDog;
 await browser.close();
})();
Source

pub fn subscribe_event( &self, ) -> Result<impl Stream<Item = Result<Event, BroadcastStreamRecvError>>, Error>

Trait Implementations§

Source§

impl Clone for Frame

Source§

fn clone(&self) -> Frame

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl PartialEq for Frame

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

§

impl Freeze for Frame

§

impl RefUnwindSafe for Frame

§

impl Send for Frame

§

impl Sync for Frame

§

impl Unpin for Frame

§

impl UnwindSafe for Frame

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.