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 (implemented in Phase 3) to navigate to URLs.
§Example
use playwright_core::protocol::{Playwright, ScreenshotOptions, ScreenshotType};
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#"
<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 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!')").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 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 fn url(&self) -> String
pub fn url(&self) -> String
Returns the current URL of the page.
This returns the last committed URL. 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 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 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 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 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(&self, expression: &str) -> Result<()>
pub async fn evaluate(&self, expression: &str) -> Result<()>
Evaluates JavaScript in the page context.
Executes the provided JavaScript expression or function within the page’s context and returns the result. The return value must be JSON-serializable.
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 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 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.