Core concepts

Playwright provides a set of APIs to automate Chromium, Firefox and WebKit browsers. By using the Playwright API, you can write JavaScript code to create new browser pages, navigate to URLs and then interact with elements on a page.

Along with a test runner Playwright can be used to automate user interactions to validate and test web applications. The Playwright API enables this through the following primitives.

Browser

A Browser refers to an instance of Chromium, Firefox or WebKit. Playwright scripts generally start with launching a browser instance and end with closing the browser. Browser instances can be launched in headless (without a GUI) or headful mode.

  1. const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
  2. const browser = await chromium.launch({ headless: false });
  3. await browser.close();

Launching a browser instance can be expensive, and Playwright is designed to maximize what a single instance can do through multiple browser contexts.

API reference

Browser contexts

A BrowserContext is an isolated incognito-alike session within a browser instance. Browser contexts are fast and cheap to create. Browser contexts can be used to parallelize isolated test executions.

  1. const browser = await chromium.launch();
  2. const context = await browser.newContext();

Browser contexts can also be used to emulate multi-page scenarios involving mobile devices, permissions, locale and color scheme.

  1. const { devices } = require('playwright');
  2. const iPhone = devices['iPhone 11 Pro'];
  3. const context = await browser.newContext({
  4. ...iPhone,
  5. permissions: ['geolocation'],
  6. geolocation: { latitude: 52.52, longitude: 13.39},
  7. colorScheme: 'dark',
  8. locale: 'de-DE'
  9. });

API reference

Pages and frames

A Browser context can have multiple pages. A Page refers to a single tab or a popup window within a browser context. It should be used to navigate to URLs and interact with the page content.

  1. // Create a page.
  2. const page = await context.newPage();
  3. // Navigate explicitly, similar to entering a URL in the browser.
  4. await page.goto('http://example.com');
  5. // Fill an input.
  6. await page.fill('#search', 'query');
  7. // Navigate implicitly by clicking a link.
  8. await page.click('#submit');
  9. // Expect a new url.
  10. console.log(page.url());
  11. // Page can navigate from the script - this will be picked up by Playwright.
  12. window.location.href = 'https://example.com';

Read more on page navigation and loading.

A page can have one or more Frame objects attached to it. Each page has a main frame and page-level interactions (like click) are assumed to operate in the main frame.

A page can have additional frames attached with the iframe HTML tag. These frames can be accessed for interactions inside the frame.

  1. // Get frame using the frame's name attribute
  2. const frame = page.frame('frame-login');
  3. // Get frame using frame's URL
  4. const frame = page.frame({ url: /.*domain.*/ });
  5. // Get frame using any other selector
  6. const frameElementHandle = await page.$('.frame-class');
  7. const frame = await frameElementHandle.contentFrame();
  8. // Interact with the frame
  9. await frame.fill('#username-input', 'John');

API reference

Selectors

Playwright can search for elements using CSS selectors, XPath selectors, HTML attributes like id, data-test-id and even text content.

You can explicitly specify the selector engine you are using or let Playwright detect it.

All selector engines except for XPath pierce shadow DOM by default. If you want to enforce regular DOM selection, you can use the *:light versions of the selectors. You don’t typically need to though.

Learn more about selectors and selector engines here.

Some examples below:

  1. // Using data-test-id= selector engine
  2. await page.click('data-test-id=foo');
  1. // CSS and XPath selector engines are automatically detected
  2. await page.click('div');
  3. await page.click('//html/body/div');
  1. // Find node by text substring
  2. await page.click('text=Hello w');
  1. // Explicit CSS and XPath notation
  2. await page.click('css=div');
  3. await page.click('xpath=//html/body/div');
  1. // Only search light DOM, outside WebComponent shadow DOM:
  2. await page.click('css:light=div');

Selectors using the same or different engines can be combined using the >> separator. For example,

  1. // Click an element with text 'Sign Up' inside of a #free-month-promo.
  2. await page.click('#free-month-promo >> text=Sign Up');
  1. // Capture textContent of a section that contains an element with text 'Selectors'.
  2. const sectionText = await page.$eval('*css=section >> text=Selectors', e => e.textContent);

Auto-waiting

Actions like click and fill auto-wait for the element to be visible and actionable. For example, click will:

  • wait for an element with the given selector to appear in the DOM
  • wait for it to become visible: have non-empty bounding box and no visibility:hidden
  • wait for it to stop moving: for example, wait until css transition finishes
  • scroll the element into view
  • wait for it to receive pointer events at the action point: for example, wait until element becomes non-obscured by other elements
  • retry if the element is detached during any of the above checks
  1. // Playwright waits for #search element to be in the DOM
  2. await page.fill('#search', 'query');
  1. // Playwright waits for element to stop animating
  2. // and accept clicks.
  3. await page.click('#search');

You can explicitly wait for an element to appear in the DOM or to become visible:

  1. // Wait for #search to appear in the DOM.
  2. await page.waitForSelector('#search', { state: 'attached' });
  3. // Wait for #promo to become visible, for example with `visibility:visible`.
  4. await page.waitForSelector('#promo');

… or to become hidden or detached

  1. // Wait for #details to become hidden, for example with `display:none`.
  2. await page.waitForSelector('#details', { state: 'hidden' });
  3. // Wait for #promo to be removed from the DOM.
  4. await page.waitForSelector('#promo', { state: 'detached' });

API reference

Execution contexts: Node.js and Browser

Playwright scripts run in your Node.js environment. You page scripts run in the browser page environment. Those environments don’t intersect, they are running in different virtual machines in different processes and even potentially on different computers.

The page.evaluate API can run a JavaScript function in the context of the web page and bring results back to the Node.js environment. Browser globals like window and document can be used in evaluate.

  1. const href = await page.evaluate(() => document.location.href);

If the result is a Promise or if the function is asynchronous evaluate will automatically wait until it’s resolved:

  1. const status = await page.evaluate(async () => {
  2. const response = await fetch(location.href);
  3. return response.status;
  4. });

Evaluation

Functions passed inside page.evaluate can accept parameters. These parameters are serialized and sent into your web page over the wire. You can pass primitive types, JSON-alike objects and remote object handles received from the page.

Right:

  1. const data = { text: 'some data', value: 1 };
  2. // Pass |data| as a parameter.
  3. const result = await page.evaluate(data => {
  4. window.myApp.use(data);
  5. }, data);

Wrong:

  1. const data = { text: 'some data', value: 1 };
  2. const result = await page.evaluate(() => {
  3. // There is no |data| in the web page.
  4. window.myApp.use(data);
  5. });

API reference

Object & Element handles

Playwright can create Node-side handles to the page DOM elements or any other objects inside the page. These handles live in the Node.js process, whereas the actual objects reside in browser.

There are two types of handles:

  • JSHandle to reference any JavaScript objects in the page
  • ElementHandle to reference DOM elements in the page

Note that since any DOM element in the page is also a JavaScript object, Playwright’s ElementHandle extends JSHandle.

Handles Lifecycle

Example: ElementHandle

  1. // The first parameter of the elementHandle.evaluate callback is the element handle points to.
  2. const ulElementHandle = await page.$('ul');
  3. await ulElementHandle.evaluate(ulElement => getComputedStyle(ulElement).getPropertyValue('display'));

Handles can also be passed as arguments to page.evaluate function:

  1. // In the page API, you can pass handle as a parameter.
  2. const ulElementHandle = await page.$('ul');
  3. await page.evaluate(uiElement => getComputedStyle(uiElement).getPropertyValue('display'), uiElement);

Example: JSHandle

  1. // Create a new array in the page, write a reference to it in
  2. // window.myArray and get a handle to it.
  3. const myArrayHandle = await page.evaluateHandle(() => {
  4. window.myArray = [1];
  5. return myArray;
  6. });
  7. // Get current length of the array using the handle.
  8. const length = await page.evaluate(
  9. (arg) => arg.myArray.length,
  10. { myArray: myArrayHandle }
  11. );
  12. // Add one more element to the array using the handle
  13. await page.evaluate((arg) => arg.myArray.push(arg.newElement), {
  14. myArray: myArrayHandle,
  15. newElement: 2
  16. });
  17. // Get current length of the array using window.myArray reference.
  18. const newLength = await page.evaluate(() => window.myArray.length);
  19. // Release the object when it's no longer needed.
  20. await myArrayHandle.dispose();

API reference