YouTip LogoYouTip

Playwright Core Api

# Playwright Core API Reference This reference guide covers the core classes and APIs of the Playwright Library. Playwright is a powerful framework for Web Testing and Automation, allowing you to control Chromium, Firefox, and WebKit with a single API. --- ## Introduction to Playwright Core Architecture Playwright's architecture is hierarchical and designed to isolate browser sessions efficiently. Understanding the relationship between these core classes is key to writing robust automation scripts: 1. **Playwright**: The entry point to the library. 2. **BrowserType**: Represents a specific browser engine (e.g., Chromium, Firefox, WebKit) used to launch or connect to a browser. 3. **Browser**: A running browser instance. 4. **BrowserContext**: An isolated, incognito-like session within a Browser instance. Contexts are fast and cheap to create, making them ideal for parallel test execution. 5. **Page**: A single tab or window within a BrowserContext. --- ## Playwright Class The `Playwright` class is the entry point for launching and interacting with browsers, managing selectors, and handling API requests. ### Properties & Methods | Property / Method | Return Type | Description | | :--- | :--- | :--- | | `playwright.chromium` | `BrowserType` | Returns the Chromium `BrowserType` instance. | | `playwright.firefox` | `BrowserType` | Returns the Firefox `BrowserType` instance. | | `playwright.webkit` | `BrowserType` | Returns the WebKit `BrowserType` instance. | | `playwright.request` | `APIRequest` | Returns the `APIRequest` instance for sending web requests. | | `playwright.selectors` | `Selectors` | Returns the `Selectors` instance to register custom selector engines. | --- ## BrowserType Class The `BrowserType` class provides methods to launch a browser instance or connect to an existing one. ### Methods | Method | Return Type | Description | | :--- | :--- | :--- | | `browserType.launch()` | `Promise` | Launches a new browser instance. | | `browserType.launchPersistentContext(userDataDir, )` | `Promise` | Launches a browser instance with a persistent context (uses a local user data directory). | | `browserType.connect(wsEndpoint, )` | `Promise` | Connects to an already running browser instance via a WebSocket endpoint. | | `browserType.connectOverCDP(endpointURL, )` | `Promise` | Connects to an active browser via the Chrome DevTools Protocol (CDP). | | `browserType.executablePath()` | `string` | Returns the path to the browser's executable file. | | `browserType.name()` | `string` | Returns the browser name (e.g., `chromium`, `firefox`, `webkit`). | --- ## Browser Class A `Browser` represents an instance of a running browser (Chromium, Firefox, or WebKit). ### Methods & Properties | Method / Property | Return Type | Description | | :--- | :--- | :--- | | `browser.newContext()` | `Promise` | Creates a new, isolated `BrowserContext`. | | `browser.newPage()` | `Promise` | Creates a new `Page` inside a new `BrowserContext` (convenience method). | | `browser.contexts()` | `Array` | Returns an array of all open browser contexts. | | `browser.close()` | `Promise` | Closes the browser and all of its associated contexts and pages. | | `browser.browserType()` | `BrowserType` | Returns the `BrowserType` that this browser belongs to. | | `browser.version()` | `string` | Returns the version of the browser. | | `browser.isConnected()` | `boolean` | Returns whether the browser is connected to the client. | --- ## BrowserContext Class `BrowserContext` provides a way to operate multiple independent browser sessions with fully isolated cookies, local storage, and permissions. ### Methods | Method | Return Type | Description | | :--- | :--- | :--- | | `context.newPage()` | `Promise` | Creates a new page (tab) in the context. | | `context.pages()` | `Array` | Returns all open pages within this context. | | `context.close()` | `Promise` | Closes the context and all associated pages. | | `context.cookies()` | `Promise>` | Retrieves cookies for the specified URLs (or all cookies if omitted). | | `context.addCookies(cookies)` | `Promise` | Adds cookies to the context. | | `context.clearCookies()` | `Promise` | Clears all cookies from the context. | | `context.storageState()` | `Promise` | Returns the current storage state (cookies + local storage) for authentication reuse. | | `context.grantPermissions(permissions, )` | `Promise` | Grants specific permissions (e.g., `'geolocation'`, `'notifications'`) to an origin. | | `context.clearPermissions()` | `Promise` | Clears all granted permissions. | | `context.setGeolocation(geolocation)` | `Promise` | Sets the default geolocation for pages in this context. | | `context.setExtraHTTPHeaders(headers)` | `Promise` | Sets extra HTTP headers to be sent with every request in this context. | | `context.route(url, handler)` | `Promise` | Intercepts network requests matching the URL pattern. | | `context.unroute(url, )` | `Promise` | Removes a network routing rule. | | `context.exposeFunction(name, callback)` | `Promise` | Exposes a Node.js function to the browser's window object. | | `context.exposeBinding(name, callback)` | `Promise` | Exposes a binding to the browser's window object, passing Playwright context info. | --- ## BrowserServer Class A `BrowserServer` represents a browser process started via `browserType.launchServer()`. This is typically used for remote execution setups. ### Methods | Method | Return Type | Description | | :--- | :--- | :--- | | `browserServer.wsEndpoint()` | `string` | Returns the WebSocket endpoint URL to connect to this server. | | `browserServer.close()` | `Promise` | Gracefully closes the server and the browser process. | | `browserServer.kill()` | `Promise` | Forcefully terminates the browser process. | --- ## Code Examples ### 1. Basic Browser Launch and Page Interaction This example demonstrates how to use `chromium` to launch a browser, create a context, open a page, and navigate to a website. ```javascript const { chromium } = require('playwright'); (async () => { // 1. Launch the browser const browser = await chromium.launch({ headless: false }); // 2. Create an isolated browser context const context = await browser.newContext(); // 3. Open a new page (tab) const page = await context.newPage(); // 4. Navigate to a URL await page.goto('https://example.com'); console.log('Page Title:', await page.title()); // 5. Clean up and close await browser.close(); })(); ``` ### 2. Reusing Authentication State (Storage State) Save login credentials (cookies and local storage) to a file and reuse them in subsequent contexts to bypass login steps. ```javascript const { chromium } = require('playwright'); (async () => { const browser = await chromium.launch(); const context = await browser.newContext(); const page = await context.newPage(); // Perform login steps await page.goto('https://example.com/login'); await page.fill('#username', 'myUser'); await page.fill('#password', 'myPassword'); await page.click('#submit-button'); await page.waitForNavigation(); // Save storage state to a file await context.storageState({ path: 'state.json' }); await browser.close(); // Create a new context using the saved state const newBrowser = await chromium.launch(); const authenticatedContext = await newBrowser.newContext({ storageState: 'state.json' }); const newPage = await authenticatedContext.newPage(); // This page will load already logged in await newPage.goto('https://example.com/dashboard'); await newBrowser.close(); })(); ``` --- ## Considerations & Best Practices * **Prefer Contexts over Browsers**: Creating a new `Browser` instance is resource-heavy. For test isolation, launch the browser once and create a new `BrowserContext` for each test case. * **Headless Mode**: By default, `browserType.launch()` runs in headless mode (no visible UI). Set `{ headless: false }` during development and debugging. * **Resource Cleanup**: Always wrap your automation code in `try...finally` blocks or ensure `await browser.close()` is called to prevent orphaned browser processes from consuming system memory.
← Playwright Locator ApiPlaywright Best Practices β†’

YouTip © 2024-2026 | Home | Learn Technology, Build Dreams!

All content is for educational and learning purposes only.