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
impl Frame
pub(crate) fn new(inner: Weak<Impl>) -> Self
pub fn url(&self) -> Result<String, Error>
Sourcepub fn name(&self) -> Result<String, Error>
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.
pub fn page(&self) -> Result<Option<Page>, Error>
Sourcepub fn parent_frame(&self) -> Result<Option<Frame>, Error>
pub fn parent_frame(&self) -> Result<Option<Frame>, Error>
Parent frame, if any. Detached frames and main frames return null.
pub fn child_frames(&self) -> Result<Vec<Frame>, Error>
Sourcepub fn goto_builder<'a>(&self, url: &'a str) -> GotoBuilder<'a, '_>
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
timeoutis 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.gotoeither throws an error or returns a main resource response. The only exceptions are navigation toabout:blankor navigation to the same URL with a different hash, which would succeed and returnnull. NOTE: Headless mode doesn’t support navigation to a PDF document. See the upstream issue.
Sourcepub fn click_builder<'a>(&self, selector: &'a str) -> ClickBuilder<'a>
pub fn click_builder<'a>(&self, selector: &'a str) -> ClickBuilder<'a>
This method clicks an element matching selector by performing the following steps:
- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Wait for actionability checks on the matched element, unless
forceoption 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 specifiedposition. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set.
When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing
zero timeout disables this.
Sourcepub fn dblclick_builder<'a>(&self, selector: &'a str) -> DblClickBuilder<'a>
pub fn dblclick_builder<'a>(&self, selector: &'a str) -> DblClickBuilder<'a>
This method double clicks an element matching selector by performing the following steps:
- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Wait for actionability checks on the matched element, unless
forceoption 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 specifiedposition. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set. Note that if the first click of thedblclick()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 twoclickevents and a singledblclickevent.
Sourcepub fn tap_builder<'a>(&self, selector: &'a str) -> TapBuilder<'a>
pub fn tap_builder<'a>(&self, selector: &'a str) -> TapBuilder<'a>
This method taps an element matching selector by performing the following steps:
- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Wait for actionability checks on the matched element, unless
forceoption 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 specifiedposition. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption 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 thehasTouchoption of the browser context be set to true.
Sourcepub fn fill_builder<'a, 'b>(
&self,
selector: &'a str,
value: &'b str,
) -> FillBuilder<'a, 'b>
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.
Sourcepub async fn focus(
&self,
selector: &str,
timeout: Option<f64>,
) -> Result<(), Arc<Error>>
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.
Sourcepub async fn text_content(
&self,
selector: &str,
timeout: Option<f64>,
) -> Result<Option<String>, Arc<Error>>
pub async fn text_content( &self, selector: &str, timeout: Option<f64>, ) -> Result<Option<String>, Arc<Error>>
Returns element.textContent.
Sourcepub async fn inner_text(
&self,
selector: &str,
timeout: Option<f64>,
) -> Result<String, Arc<Error>>
pub async fn inner_text( &self, selector: &str, timeout: Option<f64>, ) -> Result<String, Arc<Error>>
Returns element.innerText.
Sourcepub async fn inner_html(
&self,
selector: &str,
timeout: Option<f64>,
) -> Result<String, Arc<Error>>
pub async fn inner_html( &self, selector: &str, timeout: Option<f64>, ) -> Result<String, Arc<Error>>
Returns element.innerHTML.
Sourcepub async fn get_attribute(
&self,
selector: &str,
name: &str,
timeout: Option<f64>,
) -> Result<Option<String>, Arc<Error>>
pub async fn get_attribute( &self, selector: &str, name: &str, timeout: Option<f64>, ) -> Result<Option<String>, Arc<Error>>
Returns element attribute value.
pub async fn query_selector( &self, selector: &str, ) -> Result<Option<ElementHandle>, Arc<Error>>
pub async fn query_selector_all( &self, selector: &str, ) -> Result<Vec<ElementHandle>, Arc<Error>>
Sourcepub async fn frame_element(&self) -> Result<ElementHandle, Arc<Error>>
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); // -> trueSourcepub fn wait_for_selector_builder<'a>(
&self,
selector: &'a str,
) -> WaitForSelectorBuilder<'a>
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();
})();pub async fn title(&self) -> Result<String, Arc<Error>>
Sourcepub fn type_builder<'a, 'b>(
&self,
selector: &'a str,
text: &'b str,
) -> TypeBuilder<'a, 'b>
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 userSourcepub fn press_builder<'a, 'b>(
&self,
selector: &'a str,
key: &'b str,
) -> PressBuilder<'a, 'b>
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.
Sourcepub fn hover_builder<'a>(&self, selector: &'a str) -> HoverBuilder<'a>
pub fn hover_builder<'a>(&self, selector: &'a str) -> HoverBuilder<'a>
This method hovers over an element matching selector by performing the following steps:
- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Wait for actionability checks on the matched element, unless
forceoption 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 specifiedposition. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set.
When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing
zero timeout disables this.
pub async fn is_checked( &self, selector: &str, timeout: Option<f64>, ) -> Result<bool, Arc<Error>>
pub async fn is_disabled( &self, selector: &str, timeout: Option<f64>, ) -> Result<bool, Arc<Error>>
pub async fn is_editable( &self, selector: &str, timeout: Option<f64>, ) -> Result<bool, Arc<Error>>
pub async fn is_enabled( &self, selector: &str, timeout: Option<f64>, ) -> Result<bool, Arc<Error>>
pub async fn is_visible( &self, selector: &str, timeout: Option<f64>, ) -> Result<bool, Arc<Error>>
Sourcepub async fn content<'a>(&self) -> Result<String, Arc<Error>>
pub async fn content<'a>(&self) -> Result<String, Arc<Error>>
Gets the full HTML contents of the frame, including the doctype.
pub fn set_content_builder<'a>(&self, html: &'a str) -> SetContentBuilder<'a>
Sourcepub fn check_builder<'a>(&self, selector: &'a str) -> CheckBuilder<'a>
pub fn check_builder<'a>(&self, selector: &'a str) -> CheckBuilder<'a>
This method checks an element matching selector by performing the following steps:
- Find an element 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 throws. If the element is already checked, this method returns immediately.
- Wait for actionability checks on the matched element, unless
forceoption 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
noWaitAfteroption is set. - 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.
Sourcepub fn uncheck_builder<'a>(&self, selector: &'a str) -> UncheckBuilder<'a>
pub fn uncheck_builder<'a>(&self, selector: &'a str) -> UncheckBuilder<'a>
This method checks an element matching selector by performing the following steps:
- Find an element 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 throws. If the element is already unchecked, this method returns immediately.
- Wait for actionability checks on the matched element, unless
forceoption 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
noWaitAfteroption is set. - 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.
pub async fn wait_for_timeout(&self, timeout: f64)
Sourcepub async fn add_style_tag(
&self,
content: &str,
url: Option<&str>,
) -> Result<ElementHandle, Arc<Error>>
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.
Sourcepub fn add_script_tag_builder<'a>(
&self,
content: &'a str,
) -> AddScriptTagBuilder<'a, '_, '_>
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.
pub async fn evaluate_element_handle<T>(
&self,
expression: &str,
args: Option<T>,
) -> Result<ElementHandle, Arc<Error>>where
T: Serialize,
Sourcepub async fn evaluate_js_handle<T>(
&self,
expression: &str,
arg: Option<T>,
) -> Result<JsHandle, Arc<Error>>where
T: Serialize,
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();pub async fn eval<U>(&self, expression: &str) -> Result<U, Arc<Error>>where
U: DeserializeOwned,
Sourcepub async fn evaluate<T, U>(
&self,
expression: &str,
arg: T,
) -> Result<U, Arc<Error>>where
T: Serialize,
U: DeserializeOwned,
pub async fn evaluate<T, U>(
&self,
expression: &str,
arg: T,
) -> Result<U, Arc<Error>>where
T: Serialize,
U: DeserializeOwned,
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();Sourcepub async fn evaluate_on_selector<T, U>(
&self,
selector: &str,
expression: &str,
arg: Option<T>,
) -> Result<U, Arc<Error>>where
T: Serialize,
U: DeserializeOwned,
pub async fn evaluate_on_selector<T, U>(
&self,
selector: &str,
expression: &str,
arg: Option<T>,
) -> Result<U, Arc<Error>>where
T: Serialize,
U: DeserializeOwned,
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');Sourcepub async fn evaluate_on_selector_all<T, U>(
&self,
selector: &str,
expression: &str,
arg: Option<T>,
) -> Result<U, Arc<Error>>where
T: Serialize,
U: DeserializeOwned,
pub async fn evaluate_on_selector_all<T, U>(
&self,
selector: &str,
expression: &str,
arg: Option<T>,
) -> Result<U, Arc<Error>>where
T: Serialize,
U: DeserializeOwned,
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);Sourcepub async fn dispatch_event<T>(
&self,
selector: &str,
type: &str,
event_init: Option<T>,
) -> Result<(), Arc<Error>>where
T: Serialize,
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 });Sourcepub fn select_option_builder<'a>(
&self,
selector: &'a str,
) -> SelectOptionBuilder<'a>
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');Sourcepub fn set_input_files_builder<'a>(
&self,
selector: &'a str,
file: File,
) -> SetInputFilesBuilder<'a>
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.
Sourcepub fn wait_for_function_builder<'a>(
&self,
expression: &'a str,
) -> WaitForFunctionBuilder<'a>
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();
})();