Examples
To execute your scripted browser monitors using Playwright Test API make sure your script's syntax uses the variables $context
and $page
to interact with the browser context and page respectively.
In particular:
$context
is an empty context of the browser which provides a way to operate multiple independent browser sessions. Refer Playwright BrowserContext$page
is an instance of the Playwright Page object.$page
provides methods to interact with a single tab in a browser$test
is a part of the Playwright Test API that provides a way write and execute all your test cases$expect
is a part of the Playwright Test Assestions that provides assertions to validate the state of the page.$test
and$expect
are used together to write tests in a more structured way
Warning: Scripted Browser does not support .then
notation. Please use async
/await
syntax instead.
Snippets
Here are some common snippets that you can use in your scripted browser monitors. Please note that these snippets are just examples and you can modify them as per your requirements. For any additional help, please refer to the Playwright documentation or reach out to our support team.
Navigate to a URL
All scripts begin by specifying which URL the monitor should navigate to. To specify a URL, call $page.goto("url")
:
await $page.goto('https://www.example.com');
Sequence of actions
Because Playwright is asynchronous, scripting actions can sometimes execute out of order. To force script actions to execute in order, use the await keyword:
await $page.goto('https://www.example.com');
await $page.fill('input[name="username"]', 'testuser');
You can also wrap each action in a then(function(){})
call. But, in that case, the wrapped function must return
each asynchronous function to ensure they complete before the script moves on:
$page.goto('https://www.example.com').then(function(){
return $page.click('button');
})
To connect multiple actions in sequence, wrap each action in a then(function(){})
call, and chain the calls together:
$page.goto('https://www.example.com').then(function(){
return $page.click('button');
}).then(function(){
return $page.fill('input[name="username"]', 'testuser');
})
Locate elements
Once you've specified a URL to monitor, you'll usually want to locate a particular element on the page. Locating an element verifies its presence on the page, and also allows you to interact with page elements.
You can locate elements by their class, id, link text, name or even XPath. To find these attributes, use your browser's developer tools or view your website's source code. For a list of all locator functions, see Locators: Find page elements.
Locate by CSS class
Locate an element by its HTML class
, for example class="button"
. A class is usually specified for CSS styling. When locating an element by class, the monitor will select the first element on the page that has that class:
const button = await $page.locator('.button');
// Perform an action on the element, e.g., clicking it
await button.click();
Locate by HTML ID
Locate an element by its exact HTML id
, for example id="uniqueId"
. This is a straightforward way to locate page elements, but be careful to specify an id
that isn't likely to change.
const element = await $page.locator('#uniqueId');
// Perform an action on the element, e.g., typing text
await element.fill('Some text');
Locate by link text
Locate an element by its displayed link text, for example <a href="http://example.com>your link text here</a>
. This is useful for locating links on a page.
const link = await $page.locator('a:has-text("Click me")');
// Perform an action on the element, e.g., clicking it
await link.click();
Locate by name
Locate an element by its exact HTML name
, for example name="username"
. This is most commonly used with input fields such as a search box:
const inputField = await $page.locator('[name="username"]');
// Perform an action on the element, e.g., filling the input field
await inputField.fill('myUsername');
Locate by XPath
For more complex page structures, you can use XPath to locate the target element:
const element = await $page.locator('//div[@class="example"]');
// Perform an action on the element, e.g., clicking it
await element.click();
To quickly find the XPath for a particular element, use your browser's developer tools. For example, from Chrome:
- Navigate to the target website from Chrome.
- Right-click the target element, then select Inspect element.
- From the Developer Tools panel that opens automatically, look for the highlighted target element.
- Right-click the target element, then select Copy XPath.
Interact with elements
Because a scripted monitor drives a real, Playwright-powered Chrome, Firefox, Webkit browser, scripted monitors can interact with page elements in the same way a user would. For example, the monitor can click a link, enter text in a search box, etc.
First, locate the page element, then call an interaction function:
Click page elements
To click on a link or other page element, locate the element and call the click()
function:
const link = await $page.locator('a:has-text("Click me")');
// Perform an action on the element, e.g., clicking it
await link.click();
const button = await $page.locator('.button');
// Perform an action on the element, e.g., clicking it
await button.click();
Enter text
To enter text in a field, locate the field and call the fill()
function:
const inputField = await $page.locator('[name="username"]');
// Perform an action on the element, e.g., filling the input field
await inputField.fill('myUsername');
Some fields may have default text in them. Clear these fields before sending text to them:
const inputField = await $page.locator('[name="username"]');
// Clear the field
await inputField.fill('');
// Fill the field with new text
await inputField.fill('myUsername');
Manually log results to the script log
You can also manually log monitor results to the script log. Use logging to troubleshoot a script: to discover which step of your script is failing, include a log function along with each key step in your script.
The maximum log length is 50,000 bytes. Script logs larger than 50,000 bytes are truncated.
Log static text
To log a line of static text, call console.log()
:
//Send `Hello world.` to the console log.
console.log('Hello world.');
This results in the output:
Hello world.
Pass a variable to the log function
In addition to logging static text, you can also pass variables to console.log()
:
//Declare the variable `WEBSITE_URL`
var assert = require('assert'),
WEBSITE_URL = 'https://my-website.com/';
console.log('Hello world.');
//Load the website specified in `WEBSITE_URL`
await $page.goto(WEBSITE_URL);
//Log our success to the console
console.log('Success for', WEBSITE_URL);
Hello world.
Success for https://my-website.com/
Assert and Except
You can use the $expect
object to assert that elements are present on the page, text is present, and URLs are correct. Here are some examples:
Assert that an element is present
You can use the toHaveSelector()
function to assert that an element is present on the page:
await $expect($page).toHaveSelector('button');
Assert that a text is present
To assert that a specific text is present on the page, you can use the toHaveText()
function:
await $expect($page).toHaveText('Hello, World!');
Assert that a URL is correct
To verify that the page is navigated to the correct URL, you can use the toHaveURL()
function:
await $expect($page).toHaveURL('https://www.example.com');
Miscellaneous actions
Click on an element
If you want to click on a button or a link, you can use the click()
function:
await $page.click('button');
Type text in an input field
To type text in an input field, you can use the fill()
function:
await $page.fill('input[name="username"]', 'testuser');
Wait for an element to appear
In some cases, you may need to wait for an element to appear on the page before interacting with it. You can use the waitForSelector()
function to wait for an element to appear:
await $page.waitForSelector('button');
Take a screenshot
You can take a screenshot of the page using the screenshot()
function:
await $page.screenshot({ path: 'screenshot.png' });