Page

Struct Page 

Source
pub struct Page {
    inner: Weak<Page>,
    pub keyboard: Keyboard,
    pub touch_screen: TouchScreen,
    pub mouse: Mouse,
    pub accessibility: Accessibility,
}
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§

§inner: Weak<Page>§keyboard: Keyboard§touch_screen: TouchScreen§mouse: Mouse§accessibility: Accessibility

Implementations§

Source§

impl Page

Source

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

Source

pub fn context(&self) -> BrowserContext

Source

fn main_frame_weak(&self) -> Weak<FrameImpl>

Source

pub fn main_frame(&self) -> Frame

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

Source

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

An array of all frames attached to the page.

Source

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

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

NOTE: This does not contain ServiceWorkers

Source

pub fn reload_builder(&self) -> ReloadBuilder

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

Source

pub fn go_back_builder(&self) -> GoBackBuilder

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.

Source

pub fn go_forward_builder(&self) -> GoForwardBuilder

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.

Source

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

Source

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

Source

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

Source

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

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.

Source

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

Video object associated with this page.

Source

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

Brings page to front (activates tab).

Source

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

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.

Source

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

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.

Source

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

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.

Source

pub fn screenshot_builder(&self) -> ScreenshotBuilder

Source

pub fn emulate_media_builder(&self) -> EmulateMediaBuilder

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);
Source

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

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

Source

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

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.

Source

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

Source

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

Source

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

Source§

impl Page

Shorthand of main_frame

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 fn wait_for_selector_builder<'a>( &self, selector: &'a str, ) -> WaitForSelectorBuilder<'a>

Source

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

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

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 dispatch_event<T>( &self, selector: &str, type: &str, event_init: Option<T>, ) -> Result<(), 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,

Source

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

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

Source

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

Source

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

Source

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

Source

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

Source

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

Source

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

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

Source

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

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.

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]

Source

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

Source

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

Source

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

Source

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

Source

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

Source

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

Source

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

Source

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

Source

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

Source

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

Source

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

Source

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

Source

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

Source

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

Source

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

Source

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

Source

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

Source

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

Trait Implementations§

Source§

impl Clone for Page

Source§

fn clone(&self) -> Page

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 Debug for Page

Source§

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

Formats the value using the given formatter. Read more
Source§

impl PartialEq for Page

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 Page

§

impl RefUnwindSafe for Page

§

impl Send for Page

§

impl Sync for Page

§

impl Unpin for Page

§

impl UnwindSafe for Page

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.