pub struct Page { /* private fields */ }Expand description
Page represents a web page within a browser context.
A Page is created when you call BrowserContext::new_page() or Browser::new_page().
Each page is an isolated tab/window within its parent context.
Initially, pages are navigated to “about:blank”. Use navigation methods Use navigation methods to navigate to URLs.
§Example
use playwright_rs::protocol::{
Playwright, ScreenshotOptions, ScreenshotType, AddStyleTagOptions, AddScriptTagOptions,
EmulateMediaOptions, Media, ColorScheme, Viewport,
};
use std::path::PathBuf;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let playwright = Playwright::launch().await?;
let browser = playwright.chromium().launch().await?;
let page = browser.new_page().await?;
// Demonstrate url() - initially at about:blank
assert_eq!(page.url(), "about:blank");
// Demonstrate goto() - navigate to a page
let html = r#"<!DOCTYPE html>
<html>
<head><title>Test Page</title></head>
<body>
<h1 id="heading">Hello World</h1>
<p>First paragraph</p>
<p>Second paragraph</p>
<button onclick="alert('Alert!')">Alert</button>
<a href="data:text/plain,file" download="test.txt">Download</a>
</body>
</html>
"#;
// Data URLs may not return a response (this is normal)
let _response = page.goto(&format!("data:text/html,{}", html), None).await?;
// Demonstrate title()
let title = page.title().await?;
assert_eq!(title, "Test Page");
// Demonstrate content() - returns full HTML including DOCTYPE
let content = page.content().await?;
assert!(content.contains("<!DOCTYPE html>") || content.to_lowercase().contains("<!doctype html>"));
assert!(content.contains("<title>Test Page</title>"));
assert!(content.contains("Hello World"));
// Demonstrate locator()
let heading = page.locator("#heading").await;
let text = heading.text_content().await?;
assert_eq!(text, Some("Hello World".to_string()));
// Demonstrate query_selector()
let element = page.query_selector("h1").await?;
assert!(element.is_some(), "Should find the h1 element");
// Demonstrate query_selector_all()
let paragraphs = page.query_selector_all("p").await?;
assert_eq!(paragraphs.len(), 2);
// Demonstrate evaluate()
page.evaluate::<(), ()>("console.log('Hello from Playwright!')", None).await?;
// Demonstrate evaluate_value()
let result = page.evaluate_value("1 + 1").await?;
assert_eq!(result, "2");
// Demonstrate screenshot()
let bytes = page.screenshot(None).await?;
assert!(!bytes.is_empty());
// Demonstrate screenshot_to_file()
let temp_dir = std::env::temp_dir();
let path = temp_dir.join("playwright_doctest_screenshot.png");
let bytes = page.screenshot_to_file(&path, Some(
ScreenshotOptions::builder()
.screenshot_type(ScreenshotType::Png)
.build()
)).await?;
assert!(!bytes.is_empty());
// Demonstrate reload()
// Data URLs may not return a response on reload (this is normal)
let _response = page.reload(None).await?;
// Demonstrate route() - network interception
page.route("**/*.png", |route| async move {
route.abort(None).await
}).await?;
// Demonstrate on_download() - download handler
page.on_download(|download| async move {
println!("Download started: {}", download.url());
Ok(())
}).await?;
// Demonstrate on_dialog() - dialog handler
page.on_dialog(|dialog| async move {
println!("Dialog: {} - {}", dialog.type_(), dialog.message());
dialog.accept(None).await
}).await?;
// Demonstrate add_style_tag() - inject CSS
page.add_style_tag(
AddStyleTagOptions::builder()
.content("body { background-color: blue; }")
.build()
).await?;
// Demonstrate set_extra_http_headers() - set page-level headers
let mut headers = std::collections::HashMap::new();
headers.insert("x-custom-header".to_string(), "value".to_string());
page.set_extra_http_headers(headers).await?;
// Demonstrate emulate_media() - emulate print media type
page.emulate_media(Some(
EmulateMediaOptions::builder()
.media(Media::Print)
.color_scheme(ColorScheme::Dark)
.build()
)).await?;
// Demonstrate add_script_tag() - inject a script
page.add_script_tag(Some(
AddScriptTagOptions::builder()
.content("window.injectedByScriptTag = true;")
.build()
)).await?;
// Demonstrate pdf() - generate PDF (Chromium only)
let pdf_bytes = page.pdf(None).await?;
assert!(!pdf_bytes.is_empty());
// Demonstrate set_viewport_size() - responsive testing
let mobile_viewport = Viewport {
width: 375,
height: 667,
};
page.set_viewport_size(mobile_viewport).await?;
// Demonstrate close()
page.close().await?;
browser.close().await?;
Ok(())
}Implementations§
Source§impl Page
impl Page
Sourcepub fn new(
parent: Arc<dyn ChannelOwner>,
type_name: String,
guid: Arc<str>,
initializer: Value,
) -> Result<Self>
pub fn new( parent: Arc<dyn ChannelOwner>, type_name: String, guid: Arc<str>, initializer: Value, ) -> Result<Self>
Creates a new Page from protocol initialization
This is called by the object factory when the server sends a __create__ message
for a Page object.
§Arguments
parent- The parent BrowserContext objecttype_name- The protocol type name (“Page”)guid- The unique identifier for this pageinitializer- The initialization data from the server
§Errors
Returns error if initializer is malformed
Sourcepub async fn main_frame(&self) -> Result<Frame>
pub async fn main_frame(&self) -> Result<Frame>
Returns the main frame of the page.
The main frame is where navigation and DOM operations actually happen.
Sourcepub fn url(&self) -> String
pub fn url(&self) -> String
Returns the current URL of the page.
This returns the last committed URL, including hash fragments from anchor navigation. Initially, pages are at “about:blank”.
Sourcepub async fn close(&self) -> Result<()>
pub async fn close(&self) -> Result<()>
Closes the page.
This is a graceful operation that sends a close command to the page and waits for it to shut down properly.
§Errors
Returns error if:
- Page has already been closed
- Communication with browser process fails
Sourcepub fn is_closed(&self) -> bool
pub fn is_closed(&self) -> bool
Returns whether the page has been closed.
Returns true after close() has been called on this page, or after the
page receives a close event from the server (e.g. when the browser context
is closed).
See: https://playwright.dev/docs/api/class-page#page-is-closed
Sourcepub async fn set_default_timeout(&self, timeout: f64)
pub async fn set_default_timeout(&self, timeout: f64)
Sets the default timeout for all operations on this page.
The timeout applies to actions such as click, fill, locator.wait_for, etc.
Pass 0 to disable timeouts.
This stores the value locally so that subsequent action calls use it when no explicit timeout is provided, and also notifies the Playwright server so it can apply the same default on its side.
§Arguments
timeout- Timeout in milliseconds
See: https://playwright.dev/docs/api/class-page#page-set-default-timeout
Sets the default timeout for navigation operations on this page.
The timeout applies to navigation actions such as goto, reload,
go_back, and go_forward. Pass 0 to disable timeouts.
§Arguments
timeout- Timeout in milliseconds
See: https://playwright.dev/docs/api/class-page#page-set-default-navigation-timeout
Sourcepub fn default_timeout_ms(&self) -> f64
pub fn default_timeout_ms(&self) -> f64
Returns the current default action timeout in milliseconds.
Returns the current default navigation timeout in milliseconds.
Sourcepub async fn frames(&self) -> Result<Vec<Frame>>
pub async fn frames(&self) -> Result<Vec<Frame>>
Returns all frames in the page, including the main frame.
Currently returns only the main (top-level) frame. Iframe enumeration is not yet implemented and will be added in a future release.
§Errors
Returns error if:
- Page has been closed
- Communication with browser process fails
Sourcepub async fn goto(
&self,
url: &str,
options: Option<GotoOptions>,
) -> Result<Option<Response>>
pub async fn goto( &self, url: &str, options: Option<GotoOptions>, ) -> Result<Option<Response>>
Navigates to the specified URL.
Returns None when navigating to URLs that don’t produce responses (e.g., data URLs,
about:blank). This matches Playwright’s behavior across all language bindings.
§Arguments
url- The URL to navigate tooptions- Optional navigation options (timeout, wait_until)
§Errors
Returns error if:
- URL is invalid
- Navigation timeout (default 30s)
- Network error
Sourcepub fn context(&self) -> Result<BrowserContext>
pub fn context(&self) -> Result<BrowserContext>
Returns the browser context that the page belongs to.
Sourcepub async fn pause(&self) -> Result<()>
pub async fn pause(&self) -> Result<()>
Pauses script execution.
Playwright will stop executing the script and wait for the user to either press “Resume” in the page overlay or in the debugger.
Sourcepub async fn content(&self) -> Result<String>
pub async fn content(&self) -> Result<String>
Returns the full HTML content of the page, including the DOCTYPE.
This method retrieves the complete HTML markup of the page, including the doctype declaration and all DOM elements.
See: https://playwright.dev/docs/api/class-page#page-content
Sourcepub async fn set_content(
&self,
html: &str,
options: Option<GotoOptions>,
) -> Result<()>
pub async fn set_content( &self, html: &str, options: Option<GotoOptions>, ) -> Result<()>
Sets the content of the page.
See: https://playwright.dev/docs/api/class-page#page-set-content
Sourcepub async fn wait_for_load_state(&self, state: Option<WaitUntil>) -> Result<()>
pub async fn wait_for_load_state(&self, state: Option<WaitUntil>) -> Result<()>
Waits for the required load state to be 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 the current
document has already reached the required state, resolves immediately.
See: https://playwright.dev/docs/api/class-page#page-wait-for-load-state
Sourcepub async fn wait_for_url(
&self,
url: &str,
options: Option<GotoOptions>,
) -> Result<()>
pub async fn wait_for_url( &self, url: &str, options: Option<GotoOptions>, ) -> Result<()>
Waits for the main frame to navigate to a URL matching the given string or glob pattern.
See: https://playwright.dev/docs/api/class-page#page-wait-for-url
Sourcepub async fn locator(&self, selector: &str) -> Locator
pub async fn locator(&self, selector: &str) -> Locator
Creates a locator for finding elements on the page.
Locators are the central piece of Playwright’s auto-waiting and retry-ability. They don’t execute queries until an action is performed.
§Arguments
selector- CSS selector or other locating strategy
See: https://playwright.dev/docs/api/class-page#page-locator
Sourcepub async fn get_by_text(&self, text: &str, exact: bool) -> Locator
pub async fn get_by_text(&self, text: &str, exact: bool) -> Locator
Returns a locator that matches elements containing the given text.
By default, matching is case-insensitive and searches for a substring.
Set exact to true for case-sensitive exact matching.
See: https://playwright.dev/docs/api/class-page#page-get-by-text
Sourcepub async fn get_by_label(&self, text: &str, exact: bool) -> Locator
pub async fn get_by_label(&self, text: &str, exact: bool) -> Locator
Returns a locator that matches elements by their associated label text.
See: https://playwright.dev/docs/api/class-page#page-get-by-label
Sourcepub async fn get_by_placeholder(&self, text: &str, exact: bool) -> Locator
pub async fn get_by_placeholder(&self, text: &str, exact: bool) -> Locator
Returns a locator that matches elements by their placeholder text.
See: https://playwright.dev/docs/api/class-page#page-get-by-placeholder
Sourcepub async fn get_by_alt_text(&self, text: &str, exact: bool) -> Locator
pub async fn get_by_alt_text(&self, text: &str, exact: bool) -> Locator
Returns a locator that matches elements by their alt text.
See: https://playwright.dev/docs/api/class-page#page-get-by-alt-text
Sourcepub async fn get_by_title(&self, text: &str, exact: bool) -> Locator
pub async fn get_by_title(&self, text: &str, exact: bool) -> Locator
Returns a locator that matches elements by their title attribute.
See: https://playwright.dev/docs/api/class-page#page-get-by-title
Sourcepub async fn get_by_test_id(&self, test_id: &str) -> Locator
pub async fn get_by_test_id(&self, test_id: &str) -> Locator
Returns a locator that matches elements by their data-testid attribute.
Always uses exact matching (case-sensitive).
See: https://playwright.dev/docs/api/class-page#page-get-by-test-id
Sourcepub async fn get_by_role(
&self,
role: AriaRole,
options: Option<GetByRoleOptions>,
) -> Locator
pub async fn get_by_role( &self, role: AriaRole, options: Option<GetByRoleOptions>, ) -> Locator
Returns a locator that matches elements by their ARIA role.
See: https://playwright.dev/docs/api/class-page#page-get-by-role
Sourcepub fn keyboard(&self) -> Keyboard
pub fn keyboard(&self) -> Keyboard
Returns the keyboard instance for low-level keyboard control.
See: https://playwright.dev/docs/api/class-page#page-keyboard
Sourcepub async fn reload(
&self,
options: Option<GotoOptions>,
) -> Result<Option<Response>>
pub async fn reload( &self, options: Option<GotoOptions>, ) -> Result<Option<Response>>
Reloads the current page.
§Arguments
options- Optional reload options (timeout, wait_until)
Returns None when reloading pages that don’t produce responses (e.g., data URLs,
about:blank). This matches Playwright’s behavior across all language bindings.
Sourcepub async fn go_back(
&self,
options: Option<GotoOptions>,
) -> Result<Option<Response>>
pub async fn go_back( &self, options: Option<GotoOptions>, ) -> Result<Option<Response>>
Navigates to the previous page in history.
Returns the main resource response. In case of multiple server redirects, the navigation
will resolve with the response of the last redirect. If can not go back, returns None.
See: https://playwright.dev/docs/api/class-page#page-go-back
Sourcepub async fn go_forward(
&self,
options: Option<GotoOptions>,
) -> Result<Option<Response>>
pub async fn go_forward( &self, options: Option<GotoOptions>, ) -> Result<Option<Response>>
Navigates to the next page in history.
Returns the main resource response. In case of multiple server redirects, the navigation
will resolve with the response of the last redirect. If can not go forward, returns None.
See: https://playwright.dev/docs/api/class-page#page-go-forward
Sourcepub async fn query_selector(
&self,
selector: &str,
) -> Result<Option<Arc<ElementHandle>>>
pub async fn query_selector( &self, selector: &str, ) -> Result<Option<Arc<ElementHandle>>>
Returns the first element matching the selector, or None if not found.
See: https://playwright.dev/docs/api/class-page#page-query-selector
Sourcepub async fn query_selector_all(
&self,
selector: &str,
) -> Result<Vec<Arc<ElementHandle>>>
pub async fn query_selector_all( &self, selector: &str, ) -> Result<Vec<Arc<ElementHandle>>>
Returns all elements matching the selector.
See: https://playwright.dev/docs/api/class-page#page-query-selector-all
Sourcepub async fn screenshot(
&self,
options: Option<ScreenshotOptions>,
) -> Result<Vec<u8>>
pub async fn screenshot( &self, options: Option<ScreenshotOptions>, ) -> Result<Vec<u8>>
Takes a screenshot of the page and returns the image bytes.
See: https://playwright.dev/docs/api/class-page#page-screenshot
Sourcepub async fn screenshot_to_file(
&self,
path: &Path,
options: Option<ScreenshotOptions>,
) -> Result<Vec<u8>>
pub async fn screenshot_to_file( &self, path: &Path, options: Option<ScreenshotOptions>, ) -> Result<Vec<u8>>
Takes a screenshot and saves it to a file, also returning the bytes.
See: https://playwright.dev/docs/api/class-page#page-screenshot
Sourcepub async fn evaluate_expression(&self, expression: &str) -> Result<()>
pub async fn evaluate_expression(&self, expression: &str) -> Result<()>
Evaluates JavaScript in the page context (without return value).
Executes the provided JavaScript expression or function within the page’s context without returning a value.
See: https://playwright.dev/docs/api/class-page#page-evaluate
Sourcepub async fn evaluate<T: Serialize, U: DeserializeOwned>(
&self,
expression: &str,
arg: Option<&T>,
) -> Result<U>
pub async fn evaluate<T: Serialize, U: DeserializeOwned>( &self, expression: &str, arg: Option<&T>, ) -> Result<U>
Evaluates JavaScript in the page context with optional arguments.
Executes the provided JavaScript expression or function within the page’s context and returns the result. The return value must be JSON-serializable.
§Arguments
expression- JavaScript code to evaluatearg- Optional argument to pass to the expression (must implement Serialize)
§Returns
The result as a serde_json::Value
See: https://playwright.dev/docs/api/class-page#page-evaluate
Sourcepub async fn evaluate_value(&self, expression: &str) -> Result<String>
pub async fn evaluate_value(&self, expression: &str) -> Result<String>
Evaluates a JavaScript expression and returns the result as a String.
§Arguments
expression- JavaScript code to evaluate
§Returns
The result converted to a String
See: https://playwright.dev/docs/api/class-page#page-evaluate
Sourcepub async fn route<F, Fut>(&self, pattern: &str, handler: F) -> Result<()>
pub async fn route<F, Fut>(&self, pattern: &str, handler: F) -> Result<()>
Registers a route handler for network interception.
When a request matches the specified pattern, the handler will be called with a Route object that can abort, continue, or fulfill the request.
§Arguments
pattern- URL pattern to match (supports glob patterns like “**/*.png”)handler- Async closure that handles the route
Sourcepub async fn unroute(&self, pattern: &str) -> Result<()>
pub async fn unroute(&self, pattern: &str) -> Result<()>
Removes route handler(s) matching the given URL pattern.
§Arguments
pattern- URL pattern to remove handlers for
See: https://playwright.dev/docs/api/class-page#page-unroute
Sourcepub async fn unroute_all(
&self,
_behavior: Option<UnrouteBehavior>,
) -> Result<()>
pub async fn unroute_all( &self, _behavior: Option<UnrouteBehavior>, ) -> Result<()>
Removes all registered route handlers.
§Arguments
behavior- Optional behavior for in-flight handlers
See: https://playwright.dev/docs/api/class-page#page-unroute-all
Sourcepub async fn on_download<F, Fut>(&self, handler: F) -> Result<()>
pub async fn on_download<F, Fut>(&self, handler: F) -> Result<()>
Registers a download event handler.
The handler will be called when a download is triggered by the page. Downloads occur when the page initiates a file download (e.g., clicking a link with the download attribute, or a server response with Content-Disposition: attachment).
§Arguments
handler- Async closure that receives the Download object
See: https://playwright.dev/docs/api/class-page#page-event-download
Sourcepub async fn on_dialog<F, Fut>(&self, handler: F) -> Result<()>
pub async fn on_dialog<F, Fut>(&self, handler: F) -> Result<()>
Registers a dialog event handler.
The handler will be called when a JavaScript dialog is triggered (alert, confirm, prompt, or beforeunload). The dialog must be explicitly accepted or dismissed, otherwise the page will freeze.
§Arguments
handler- Async closure that receives the Dialog object
See: https://playwright.dev/docs/api/class-page#page-event-dialog
Sourcepub async fn on_request<F, Fut>(&self, handler: F) -> Result<()>
pub async fn on_request<F, Fut>(&self, handler: F) -> Result<()>
Sourcepub async fn on_request_finished<F, Fut>(&self, handler: F) -> Result<()>
pub async fn on_request_finished<F, Fut>(&self, handler: F) -> Result<()>
Sourcepub async fn on_request_failed<F, Fut>(&self, handler: F) -> Result<()>
pub async fn on_request_failed<F, Fut>(&self, handler: F) -> Result<()>
Sourcepub async fn on_response<F, Fut>(&self, handler: F) -> Result<()>
pub async fn on_response<F, Fut>(&self, handler: F) -> Result<()>
Sourcepub async fn on_websocket<F, Fut>(&self, handler: F) -> Result<()>
pub async fn on_websocket<F, Fut>(&self, handler: F) -> Result<()>
Adds a listener for the websocket event.
The handler will be called when a WebSocket request is dispatched.
§Arguments
handler- The function to call when the event occurs
See: https://playwright.dev/docs/api/class-page#page-on-websocket
Sourcepub async fn trigger_dialog_event(&self, dialog: Dialog)
pub async fn trigger_dialog_event(&self, dialog: Dialog)
Triggers dialog event (called by BrowserContext when dialog events arrive)
Dialog events are sent to BrowserContext and forwarded to the associated Page. This method is public so BrowserContext can forward dialog events.
Sourcepub async fn add_style_tag(
&self,
options: AddStyleTagOptions,
) -> Result<Arc<ElementHandle>>
pub async fn add_style_tag( &self, options: AddStyleTagOptions, ) -> Result<Arc<ElementHandle>>
Adds a <style> tag into the page with the desired content.
§Arguments
options- Style tag options (content, url, or path)
§Returns
Returns an ElementHandle pointing to the injected <style> tag
§Example
use playwright_rs::protocol::AddStyleTagOptions;
// With inline CSS
page.add_style_tag(
AddStyleTagOptions::builder()
.content("body { background-color: red; }")
.build()
).await?;
// With external URL
page.add_style_tag(
AddStyleTagOptions::builder()
.url("https://example.com/style.css")
.build()
).await?;
// From file
page.add_style_tag(
AddStyleTagOptions::builder()
.path("./styles/custom.css")
.build()
).await?;See: https://playwright.dev/docs/api/class-page#page-add-style-tag
Sourcepub async fn add_init_script(&self, script: &str) -> Result<()>
pub async fn add_init_script(&self, script: &str) -> Result<()>
Adds a script which would be evaluated in one of the following scenarios:
- Whenever the page is navigated
- Whenever a child frame is attached or navigated
The script is evaluated after the document was created but before any of its scripts were run.
§Arguments
script- JavaScript code to be injected into the page
§Example
page.add_init_script("window.injected = 123;").await?;See: https://playwright.dev/docs/api/class-page#page-add-init-script
Sourcepub async fn set_viewport_size(&self, viewport: Viewport) -> Result<()>
pub async fn set_viewport_size(&self, viewport: Viewport) -> Result<()>
Sets the viewport size for the page.
This method allows dynamic resizing of the viewport after page creation, useful for testing responsive layouts at different screen sizes.
§Arguments
viewport- The viewport dimensions (width and height in pixels)
§Example
// Set viewport to mobile size
let mobile = Viewport {
width: 375,
height: 667,
};
page.set_viewport_size(mobile).await?;
// Later, test desktop layout
let desktop = Viewport {
width: 1920,
height: 1080,
};
page.set_viewport_size(desktop).await?;§Errors
Returns error if:
- Page has been closed
- Communication with browser process fails
See: https://playwright.dev/docs/api/class-page#page-set-viewport-size
Sourcepub async fn bring_to_front(&self) -> Result<()>
pub async fn bring_to_front(&self) -> Result<()>
Brings this page to the front (activates the tab).
Activates the page in the browser, making it the focused tab. This is useful in multi-page tests to ensure actions target the correct page.
§Errors
Returns error if:
- Page has been closed
- Communication with browser process fails
See: https://playwright.dev/docs/api/class-page#page-bring-to-front
Sourcepub async fn set_extra_http_headers(
&self,
headers: HashMap<String, String>,
) -> Result<()>
pub async fn set_extra_http_headers( &self, headers: HashMap<String, String>, ) -> Result<()>
Sets extra HTTP headers that will be sent with every request from this page.
These headers are sent in addition to headers set on the browser context via
BrowserContext::set_extra_http_headers(). Page-level headers take precedence
over context-level headers when names conflict.
§Arguments
headers- Map of header names to values.
§Errors
Returns error if:
- Page has been closed
- Communication with browser process fails
See: https://playwright.dev/docs/api/class-page#page-set-extra-http-headers
Sourcepub async fn emulate_media(
&self,
options: Option<EmulateMediaOptions>,
) -> Result<()>
pub async fn emulate_media( &self, options: Option<EmulateMediaOptions>, ) -> Result<()>
Emulates media features for the page.
This method allows emulating CSS media features such as media, color-scheme,
reduced-motion, and forced-colors. Pass None to call with no changes.
To reset a specific feature to the browser default, use the NoOverride variant.
§Arguments
options- Optional emulation options. IfNone, this is a no-op.
§Example
// Emulate print media
page.emulate_media(Some(
EmulateMediaOptions::builder()
.media(Media::Print)
.build()
)).await?;
// Emulate dark color scheme
page.emulate_media(Some(
EmulateMediaOptions::builder()
.color_scheme(ColorScheme::Dark)
.build()
)).await?;§Errors
Returns error if:
- Page has been closed
- Communication with browser process fails
See: https://playwright.dev/docs/api/class-page#page-emulate-media
Sourcepub async fn pdf(&self, options: Option<PdfOptions>) -> Result<Vec<u8>>
pub async fn pdf(&self, options: Option<PdfOptions>) -> Result<Vec<u8>>
Generates a PDF of the page and returns it as bytes.
Note: Generating a PDF is only supported in Chromium headless. PDF generation is not supported in Firefox or WebKit.
The PDF bytes are returned. If options.path is set, the PDF will also be
saved to that file.
§Arguments
options- Optional PDF generation options
§Example
let pdf_bytes = page.pdf(None).await?;
assert!(!pdf_bytes.is_empty());§Errors
Returns error if:
- The browser is not Chromium (PDF only supported in Chromium)
- Page has been closed
- Communication with browser process fails
Sourcepub async fn add_script_tag(
&self,
options: Option<AddScriptTagOptions>,
) -> Result<Arc<ElementHandle>>
pub async fn add_script_tag( &self, options: Option<AddScriptTagOptions>, ) -> Result<Arc<ElementHandle>>
Adds a <script> tag into the page with the desired URL or content.
§Arguments
options- Optional script tag options (content, url, or path). IfNone, returns an error because no source is specified.
At least one of content, url, or path must be provided.
§Example
// With inline JavaScript
page.add_script_tag(Some(
AddScriptTagOptions::builder()
.content("window.myVar = 42;")
.build()
)).await?;
// With external URL
page.add_script_tag(Some(
AddScriptTagOptions::builder()
.url("https://example.com/script.js")
.build()
)).await?;§Errors
Returns error if:
optionsisNoneor no content/url/path is specified- Page has been closed
- Script loading fails (e.g., invalid URL)
See: https://playwright.dev/docs/api/class-page#page-add-script-tag
Sourcepub fn viewport_size(&self) -> Option<Viewport>
pub fn viewport_size(&self) -> Option<Viewport>
Returns the current viewport size of the page, or None if no viewport is set.
Returns None when the context was created with no_viewport: true. Otherwise
returns the dimensions configured at context creation time or updated via
set_viewport_size().
§Example
let context = browser.new_context_with_options(
BrowserContextOptions::builder().viewport(Viewport { width: 1280, height: 720 }).build()
).await?;
let page = context.new_page().await?;
let size = page.viewport_size().expect("Viewport should be set");
assert_eq!(size.width, 1280);
assert_eq!(size.height, 720);See: https://playwright.dev/docs/api/class-page#page-viewport-size