Struct playwright::api::page::Page[][src]

pub struct Page {
    pub keyboard: Keyboard,
    pub touch_screen: TouchScreen,
    pub mouse: Mouse,
    pub accessibility: Accessibility,
    // some fields omitted
}
Expand description

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

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

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 methods, such as on, once or removeListener.

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

page.once('load', () => console.log('Page loaded!'));

To unsubscribe from events use the removeListener method:

function logRequest(interceptedRequest) {
 console.log('A request was made:', interceptedRequest.url());
}
page.on('request', logRequest);
page.removeListener('request', logRequest);

Fields

keyboard: Keyboardtouch_screen: TouchScreenmouse: Mouseaccessibility: Accessibility

Implementations

impl Page[src]

pub fn context(&self) -> BrowserContext[src]

pub fn main_frame(&self) -> Frame[src]

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

pub fn frames(&self) -> Result<Vec<Frame>, Error>[src]

An array of all frames attached to the page.

pub fn workers(&self) -> Result<Vec<Worker>, Error>[src]

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

NOTE: This does not contain ServiceWorkers

pub fn reload_builder(&self) -> ReloadBuilder[src]

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

pub fn go_back_builder(&self) -> GoBackBuilder[src]

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.

pub fn go_forward_builder(&self) -> GoForwardBuilder[src]

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.

pub async fn set_default_navigation_timeout(
    &self,
    timeout: u32
) -> Result<(), Arc<Error>>
[src]

pub async fn set_default_timeout(&self, timeout: u32) -> Result<(), Arc<Error>>[src]

pub fn viewport_size(&self) -> Result<Option<Viewport>, Error>[src]

pub async fn set_viewport_size(
    &self,
    viewport_size: Viewport
) -> Result<(), Arc<Error>>
[src]

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.

pub fn video(&self) -> Result<Option<Video>, Error>[src]

Video object associated with this page.

pub async fn bring_to_front(&self) -> Result<(), Arc<Error>>[src]

Brings page to front (activates tab).

pub async fn add_init_script(&self, source: &str) -> Result<(), Arc<Error>>[src]

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:

Math.random = () => 42;
await page.addInitScript({ path: './preload.js' });

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

pub fn pdf_builder(&self) -> PdfBuilder<'_, '_, '_, '_, '_, '_, '_, '_, '_, '_>[src]

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 property to force rendering of exact colors.

await page.emulateMedia({media: 'screen'});
await page.pdf({path: 'page.pdf'});

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

A few examples:

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

All possible units are:

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

The format options are:

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

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

pub async fn close(
    &self,
    run_before_unload: Option<bool>
) -> Result<(), Arc<Error>>
[src]

All temporary pages will be closed when the connection is terminated, but it needs to be called explicitly to close it at any given time. 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.

pub fn screenshot_builder(&self) -> ScreenshotBuilder[src]

pub fn emulate_media_builder(&self) -> EmulateMediaBuilder[src]

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

await page.evaluate(() => matchMedia('screen').matches);
await page.evaluate(() => matchMedia('print').matches);
await page.emulateMedia({ media: 'print' });
await page.evaluate(() => matchMedia('screen').matches);
await page.evaluate(() => matchMedia('print').matches);
await page.emulateMedia({});
await page.evaluate(() => matchMedia('screen').matches);
await page.evaluate(() => matchMedia('print').matches);
await page.emulateMedia({ colorScheme: 'dark' });
await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches);
await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches);
await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').matches);

pub async fn opener(&self) -> Result<Option<Page>, Arc<Error>>[src]

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

pub async fn set_extra_http_headers<T>(
    &self,
    headers: T
) -> Result<(), Arc<Error>> where
    T: IntoIterator<Item = (String, String)>, 
[src]

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

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

pub async fn expect_event(&self, evt: EventType) -> Result<Event, Error>[src]

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

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

impl Page[src]

Shorthand of main_frame

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

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

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

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

Errors if the element is not a checkbox or radio input.

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

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

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

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

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

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

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

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

pub async fn eval<U>(&self, expression: &str) -> Result<U, Arc<Error>> where
    U: DeserializeOwned
[src]

pub async fn evaluate<T, U>(
    &self,
    expression: &str,
    arg: T
) -> Result<U, Arc<Error>> where
    T: Serialize,
    U: DeserializeOwned
[src]

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
[src]

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
[src]

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

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

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

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

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

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

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

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.

Shortcut for main frame’s [method: Frame.goto]

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

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

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

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

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

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

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

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

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

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

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

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

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

pub fn type_builer<'a, 'b>(
    &self,
    selector: &'a str,
    text: &'b str
) -> TypeBuilder<'a, 'b>
[src]

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

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

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

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

Trait Implementations

impl Clone for Page[src]

fn clone(&self) -> Page[src]

Returns a copy of the value. Read more

fn clone_from(&mut self, source: &Self)1.0.0[src]

Performs copy-assignment from source. Read more

impl Debug for Page[src]

fn fmt(&self, f: &mut Formatter<'_>) -> Result[src]

Formats the value using the given formatter. Read more

impl PartialEq<Page> for Page[src]

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

This method tests for self and other values to be equal, and is used by ==. Read more

#[must_use]
fn ne(&self, other: &Rhs) -> bool
1.0.0[src]

This method tests for !=.

Auto Trait Implementations

impl RefUnwindSafe for Page

impl Send for Page

impl Sync for Page

impl Unpin for Page

impl UnwindSafe for Page

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

pub fn type_id(&self) -> TypeId[src]

Gets the TypeId of self. Read more

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

pub fn borrow(&self) -> &T[src]

Immutably borrows from an owned value. Read more

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

pub fn borrow_mut(&mut self) -> &mut T[src]

Mutably borrows from an owned value. Read more

impl<T> From<T> for T[src]

pub fn from(t: T) -> T[src]

Performs the conversion.

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

pub fn into(self) -> U[src]

Performs the conversion.

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

pub fn to_owned(&self) -> T[src]

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

pub fn clone_into(&self, target: &mut T)[src]

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

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

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

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

Performs the conversion.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.

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

Performs the conversion.