Browser
Source: /
Browser Automation
Element Selectors
Many functions here take selector strings to identify elements. These selectors are just like CSS selectors but with a few minor additions to make them more convenient for website automation.
Common selectors:
-
By id
#thisIsTheId
-
By class
.class1.class2.class3
-
By tag
button
-
By tag & class
button.class1.class2
-
By hierarchy
div.class1 span.class2 button.class2
Methods
- back()
- block3rdPartyUrls()
- blockUrl(.
. . url) - check(selector[, on])
- checked(selector)
- clear(selector)
- clearCache()
- clearCookies()
- clearHighlight()
- clearPageLoad()
- clearRules()
- click(selector)
- clickAt(selector, x, y)
- close()
- dismissDialogs()
- doubleClick(selector)
- doubleClickAt(selector, x, y)
- emulateDevice(name)
- emulateNetworkCondition(name)
- execute(script)
- exists(selector)
- focus(selector)
- forward()
- getBrowserName()
- getBrowserVersion()
- getCookie(name)
- getCookie(url, name)
- getInnerHTML([selector])
- getInnerText([selector])
- getOpenDialog()
- getOuterHTML([selector])
- getResponseBody([httpRequest])
- getTitle()
- getUrl()
- getValue(selector)
- handleDialog(val)
- hasText(text)
- highlight(selector[, color])
- hover(selector)
- hoverAt(selector, x, y)
- ignoreHttpErrors([ignore])
- isDialogOpen()
- isVisible(selector)
- jq(script)
- listAllFrames()
- listCookies()
- listDevices()
- listFrames([selector])
- listNetworkConditions()
- listTabs()
- newPage([pageName])
- newTab()
- open(url)
- openAsync(url)
- query(selector)
- queryVisible(selector)
- reload()
- removeCookie(name)
- removeCookie(url, name)
- removeHeader(header)
- rewriteUrl(url, rewriteUrl)
- screenshot([format][, quality])
- select(selector, value)
- selectContent(selector)
- selectFrame(selector)
- selectFrameCss(selector)
- selectLatestTab()
- selectMainTab()
- selectTab(obj)
- selectTopFrame()
- setAuth(username, password)
- setCookie(name, value[, details])
- setFile(selector, file)
- setHeader(name, value)
- setUserAgent(userAgent)
- setValue(selector, value)
- startVideoCapture()
- stopVideoCapture()
- stopVideoCapture(name)
- submit(selector)
- type(selector, .
. . text) - verifyExists(selector)
- verifyNotExists(selector)
- verifyNotText(text)
- verifyRequest(url)
- verifyText(text)
- verifyTitle(title)
- waitElement(selector)
- waitElementText(selector, text)
- waitForHttpRequests(idleTimeMS)
- waitNotText(text)
- waitNotVisible(selector)
- waitPageLoad([timeoutMS])
- waitText(text)
- waitVisible(selector)
Methods
back()
Go back to the previous page.
4xx and 5xx responses on the main document trigger a failure after the page has loaded.
- See also
- module:Browser#ignoreHttpErrors
- Throws
Throws an exception when a 4xx or 5xx status code is returned for main document.
block3rdPartyUrls()
Block requests to known third party URLs
These include analytics, tracking, advertising and RUM beacons.
Example
var b = pizza.open();
// Block known 3rd party beacons and adverts
b.block3rdPartyUrls();
b.open("www.mysite.com");
blockUrl(...url)
Block requests to the given URL(s)
Accepts wildcards in each URL, but URL must be of the form:
"protocol://host/path"
The protocol, site and path parts can wildcarded partially or fully.
Examples
var b = pizza.open();
// Block any URLs from ad.doubleclick.net
// This will actually block any URL with 'ad.doubleclick.net' as part of the URL
b.blockUrl("*://ad.doubleclick.net/*");
b.open("www.mysite.com");
// Block any URLs from any doubleclick.net subdomain
b.blockUrl("*://*.doubleclick.net/*");
Parameter
Name | Type | Optional | Description |
---|---|---|---|
url |
String |
|
The string to match against Value can be repeated. |
check(selector[, on])
Check the a checkbox matching the given selector
By default this function will check the checkbox.
Example
// Check the checkbox with id 'checkBox1'
b.check("#checkBox1");
Parameters
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
the checkbox element to check |
on |
Boolean |
Yes |
Check on/true(default) or off/false. |
- Throws
Throws an exception if the element can not be found
checked(selector) → Boolean
Check if input checkbox is selected.
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
the checkbox element to check |
- Throws
Throws an exception if the element can not be found
- Returns
Boolean
true if input checkbox selected.
clear(selector)
Clear the input element text matching the given selector
Examples
// Clear the text in an input element with id 'id1'
b.clear("#id1");
// Clear the text in an input element with id 'id1'
b.clear("#input1");
b.type("#input1", Key.Backspace);
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
the element to type text into |
- Throws
Throws an exception if the element can not be found
clearCache()
Clear the browser cache
Clears both the disk cache and the in memory cache.
Example
// Load one page
var b = pizza.open();
b.open("www.mysite.com/page1");
// Now load another page on the same site, but clear the cache first
b.clearCache();
b.open("www.mysite.com/page2");
clearCookies()
Clear all browser cookies
Example
// Load one page
var b = pizza.open();
b.open("www.mysite.com/page1");
// Now load another page on the same site, but clear the cookies first
b.clearCookies();
b.open("www.mysite.com/page2");
clearHighlight()
Clears the highlight
Example
b.clearHighlight();
clearPageLoad()
Forget any page loads that happened before this function, used in conjunction with waitPageLoad().
Normally you should call this before doing something that triggers a new page to load. That way when waitPageLoad() is called you know that waitPageLoad() waits on the new page to load, and does not just detect some previous page load.
Since JavaScript executing on the page can change the URL at any time, it's not a sure fire way of making waitPageLoad() wait on the right page load. You can call the version of waitPageLoad() that waits for a specific URL to load, if this is an issue.
Example
b.openAsync("www.mysite.com");
b.waitVisible("#button1");
b.clearPageLoad();
b.click("#button1");
b.waitPageLoad();
clearRules()
Clears all URL block and rewrite rules.
Example
// Open site with ads blocked, and then without ads blocked
var b = pizza.open();
b.blockUrl("ad.doubleclick.net");
b.open("www.mysite.com");
// Remove the rule to block ads
b.clearRules();
b.open("www.mysite.com");
click(selector)
Click the first item matching the given selector.
If the item is off-screen it will be scrolled on-screen if possible..
Scrolling may not work right away, so by default this function will check that the element has moved on-screen before clicking and wait a little bit for it to move if not (max 5 retries with 500ms wait between each retry).
If this click() navigates to a new page, call waitPageLoad() to wait for the new page to load. If the page is opened in a new tab then you need to select the new tab before waiting.
Examples
// Click an element with id 'search'
b.click("#search");
// Wait for the new page to load
b.waitPageLoad();
// Click an element with id 'search', and adjust the wait for the
// element to be scrolled on-screen.
b.click("#search", { "retry": 10, "retryWaitTime": 500 });
// Wait for the new page to load
b.waitPageLoad();
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
the element to click |
- Throws
Throws an exception if the element can not be found
Throws an exception if the element is not visible
clickAt(selector, x, y)
Click the given item at the given location, emulating all JavaScript events
Example
b.clickAt("#submit", 20, 20);
Parameters
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
the element to click |
x |
Number |
|
the x offset within the given element to click on |
y |
Number |
|
the y offset within the given element to click on |
- Throws
Throws an exception if the element can not be found
Throws an exception if the element is not visible
close()
Close the browser process.
The browser object cannot be used after this call.
Example
// Open the browser at a URL close and open a new URL in a
// newly launched browser.
var b = pizza.open("www.google.com");
b.close();
b = pizza.open("www.bing.com");
- See also
- module:Browser#open
dismissDialogs()
Dismiss all current and future JavaScript dialogs.
Example
var b = pizza.open();
b.dismissDialogs();
b.open("mysitewithdialog.com");
- See also
- module:Browser#handleDialog
doubleClick(selector)
Double click the given item, emulating all JavaScript events
Example
b.doubleClick("#submit");
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
the element to click |
- Throws
Throws an exception if the element can not be found
Throws an exception if the element is not visible
doubleClickAt(selector, x, y)
Double click the given item at the given location, emulating all JavaScript events
Parameters
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
the element to click |
x |
Number |
|
the x offset within the given element to click on |
y |
Number |
|
the y offset within the given element to click on |
- Throws
Throws an exception if the element can not be found
Throws an exception if the element is not visible
emulateDevice(name)
Emulate the given device's rendering.
The viewport & device pixel ratio will be scaled to match the rendering of the device. The user agent is also changed.
Only applies to new pages that are loaded (not the current).
Examples
// Open "apple.com" while emulating an iPhone 6.
b = pizza.open();
b.emulateDevice("Apple iPhone 6");
b.open("apple.com");
// Open normally in desktop mode, then reload emulating a Galaxy S4
b = pizza.open("samsung.com");
b.emulateDevice("Samsung Galaxy S4");
b.reload();
Parameter
Name | Type | Optional | Description |
---|---|---|---|
name |
String |
|
The device to emulate. Set to null to disable device emulation. |
emulateNetworkCondition(name)
Emulate the given network condition.
Examples
// Open "bbc.com" emulating 3G latency and bandwidth constraints
b = pizza.open();
b.emulateNetworkCondition("Regular 3G");
b.open("bbc.com");
// Open "bbc.com" emulating a network latency of 50 milliseconds
b = pizza.open();
b.emulateNetworkCondition({latency: 50});
b.open("bbc.com");
// Disable a previously set network condition
b.emulateNetworkCondition({});
b.open("bbc.com");
Parameter
Name | Type | Optional | Description |
---|---|---|---|
name |
(String or Object) |
|
The network condition to emulate. Set to {} to disable network condition emulation. |
execute(script) → Object
Execute the given JavaScript in the current frame.
If there is an exception when the script is executed in the browser it will be thrown here.
Example
var elementExists =
b.execute("document.getElementBy('0') ? true : false");
Parameter
Name | Type | Optional | Description |
---|---|---|---|
script |
String |
|
The JavaScript code to execute |
- See also
- module:Browser#jq
- Returns
Object
The result of the script execution
exists(selector) → Boolean
Test if an element matching the given selector exists in the current frame/tab.
Example
// Submit form1 if it exists otherwise submit form2.
if (b.exists('#form1')) {
b.submit('#form1');
} else {
b.submit('#form2');
}
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
the CSS selector or XPATH to lookup |
- Returns
Boolean
true if at least one element that matches the selector exists / false otherwise
focus(selector)
Focus the first item matching the given selector, emulating focus/blur JavaScript events.
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
|
|
the element to focus |
forward()
Go forward in the history.
4xx and 5xx responses on the main document trigger a failure after the page has loaded.
- See also
- module:Browser#ignoreHttpErrors
- Throws
Throws an exception when a 4xx or 5xx status code is returned for main document.
getBrowserName() → String
Get the browser name.
E.g. "Google Chrome".
Example
console.log("Running test with browser: " + b.getBrowserName());
- Returns
String
the browser name
getBrowserVersion() → String
Get Version of the browser we are using
Example
console.log("Running test with browser version: " + b.getBrowserVersion());
- Returns
String
the version of the browser that was launched
getCookie(name) → module:Cookie
Get a cookie
Given a cookie name, get details about the cookie. The current domain is used.
Parameter
Name | Type | Optional | Description |
---|---|---|---|
name |
String |
|
the name of the cookie to get |
- Returns
the cookie info
getCookie(url, name) → module:Cookie
Get a cookie
Given a URL and cookie name, get details about the cookie.
Parameters
Name | Type | Optional | Description |
---|---|---|---|
url |
String |
|
the url of the cookie |
name |
String |
|
the name of the cookie to get |
- Returns
the cookie info
getInnerHTML([selector]) → String
Get the html inside the given element.
Examples
var html = b.getInnerHTML('#input1');
// Get html for entire frame
var html = b.getInnerHTML();
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
Yes |
the element to get the HTML from |
- Throws
Throws an exception if the element can not be found
- Returns
String
the inner HTML for the given element
getInnerText([selector]) → String
Get the text inside the given element
Examples
var text = b.getInnerText('#button1');
// Get all text for currently selected frame
var text = b.getInnerText();
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
Yes |
the element to get the inner text from |
- Throws
Throws an exception if the element can not be found
- Returns
String
the inner text for the given element
getOpenDialog() → module:DialogInfo
Get details about the currently open JavaScript dialog.
Example
// Make sure an alert dialog is opened with specific text
var b = pizza.open();
b.openAsync("mysitewithdialog.com");
var dialog = b.getOpenDialog();
assert.eq("alert\", dialog.type);
assert.eq("it's a dialog!", dialog.message);
- See also
- module:Browser#isDialogOpen
- Returns
module:DialogInfo
dialog info or null if no dialog open
getOuterHTML([selector]) → String
Get the html for the given element or the entire frame if no element specified.
Examples
var html = b.getOuterHTML();
var html = b.getOuterHTML("#myForm");
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
Yes |
the element to get the HTML for |
- Throws
Throws an exception if the element can not be found
- Returns
String
the outer HTML for the given element
getResponseBody([httpRequest]) → module:Data
Grab the response body for the given http request.
The HTTP requests can be gotten from pizza.result, see the example below.
Note the HTTP request actually has to be finished before this can be called.
If the item is downloading will wait until it is downloaded.
Example
b.open("www.google.com");
// Get response body of the main HTML request
var d = b.getResponseBody(pizza.getRequestByUrl("www.google.com")));
Parameter
Name | Type | Optional | Description |
---|---|---|---|
httpRequest |
HttpRequest |
Yes |
A http request that was previously made by the browser. |
- See also
- module:pizza#result
- module:TestResult#pages
- module:Page#requests
- Returns
the contents of the request
getTitle() → String
Return the page title.
Example
var title = b.getTitle();
console.log("Loaded page '" + title + "'");
- See also
- module:Browser#verifyTitle
- Returns
String
The page title
getUrl() → String
Get the current URL the browser is pointing to
Example
var b = pizza.open("www.google.com");
var url = b.getUrl();
- Returns
String
the URL the browser is pointing to
getValue(selector) → Object
Gets the value of given input form item
Example
assert.eq(b.getValue('#checkbox1'), 'on');
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
the select element to select from |
- Throws
Throws an exception if the element can not be found
- Returns
Object
the value of the given input form item
handleDialog(val)
Accept / Reject the currently displayed JavaScript dialog, if any.
Example
var b = pizza.open();
b.openAsync("mysitewithdialog.com");
// Wait for dialog to open
pizza.waitFor(function() { return b.isDialogOpen(); });
b.handleDialog();
Parameter
Name | Type | Optional | Description |
---|---|---|---|
val |
(Boolean or optional String) |
|
If true accept the dialog, if false reject, if a string fill out the window.prompt() dialog with the given text. |
- See also
- module:Browser#dismissDialogs
hasText(text) → Boolean
Check if the given text exists somewhere on the page.
Example
if (b.hasText('Accept Terms')) {
b.click("#accept");
}
Parameter
Name | Type | Optional | Description |
---|---|---|---|
text |
(String or RegExp) |
|
The text to look for on the page |
- See also
- module:Browser#verifyText
- module:Browser#verifyNotText
- module:Browser#waitText
- module:Browser#waitNotText
- module:Browser#getInnerText
- Returns
Boolean
true if the given text can be found
highlight(selector[, color])
Highlight the first element matching the selector
Only one item at a time can be highlighted. Selecting a second will remove the highlight from the first. Call clearHighlight() to remove the highlight.
An optional color can be specified for the highlight.
a - The alpha component, in the [0-1] range r - The red component, in the [0-255] range g - The green component, in the [0-255] range b - The blue component, in the [0-255] range
Examples
// Highlight button with id 'button1'
b.highlight("#button1")
// Transparent blue highlight on first <button>:
b.highlight("button", { a: 0.2, r: 0, g: 0, b: 255 })
Parameters
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
The element to select |
color |
Color |
Yes |
The color of the highlight |
hover(selector)
Hover over the first item matching the given selector, emulating all JavaScript events.
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
|
|
the element to hover over |
hoverAt(selector, x, y)
Hover over the first item matching the given selector at the given location, emulating all JavaScript events
Example
// Hover over a drop down
b.hover("#myDropDown");
// Wait for a link to be displayed
b.waitVisible("#myMenuItem");
// Now click the link
b.click("#myMenuItem");
b.waitPageLoad();
Parameters
Name | Type | Optional | Description |
---|---|---|---|
selector |
|
|
the element to hover over |
x |
|
|
the x offset within the given element |
y |
|
|
the y offset within the given element |
- Throws
Throws an exception if the element can not be found
Throws an exception if the element is not visible
ignoreHttpErrors([ignore])
Don't trigger an error on HTTP 4xx or 5xx status codes during a call to open(), waitPageLoad(), reload(), back() or forward().
Examples
b.ignoreHttpErrors(); // same as b.ignoreHttpErrors(true)
// Go to a 404 page but don't throw an error
b.open("mysite.com/404");
// Only ignore 404 errors, other 4xx and 5xx status codes will still
// throw an error
b.ignoreHttpErrors(404);
b.open("mysite.com/404");
// Turn back on http errors for all 4xx and 5xx status codes.
// You only need to do this if you turned off the error check previously.
b.ignoreHttpErrors(false);
b.open("mysite.com/404");
Parameter
Name | Type | Optional | Description |
---|---|---|---|
ignore |
(Boolean or repeatable Number) |
Yes |
if true errors will be ignored (the default) if set to false, errors will trigger the above methods to throw an exception again. If set to a list of numbers any status codes that match these numbers won't throw an exception. Defaults to |
isDialogOpen() → Boolean
Is a JavaScript modal dialog open?
Example
var b = pizza.open();
b.openAsync("mysitewithdialog.com");
// Wait for dialog to open
pizza.waitFor(function() { return b.isDialogOpen(); });
b.handleDialog(true);
- See also
- module:Browser#getOpenDialog
- Returns
Boolean
true if a JavaScript modal dialog is open, false otherwise
isVisible(selector) → Boolean
Test if an element matching the given selector is visible in the current frame/tab.
Example
// Click button1 if it exists otherwise click button2.
if (b.isVisible('#button1')) {
b.click('#button1');
} else {
b.click('#button2');
}
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
the element to search for |
- Returns
Boolean
true if the element is visible
jq(script) → Array of Object
Execute the given JavaScript jQuery expression.
Executes on all frames in the current tab.
If the normal automation functions fail or are limited in some way, jQuery to the rescue! (maybe) jQuery selectors are typically a bit richer than the selectors provided by us and since any javascript code can be executed, more complex queries can be built up.
Examples
// Click a button using jQuery
// Note the use of single quotes inside the double quoted string
b.jq("$($('button')[1]).click()")
// Change the border on certain buttons to highlight them
b.jq("$('button').css('border', '2px solid red')")
Parameter
Name | Type | Optional | Description |
---|---|---|---|
script |
String |
|
The JavaScript code to execute |
- See also
- module:Browser#execute
- Returns
Array of Object
Returns an array of results for each frame that exists on the current tab
listAllFrames() → Array of module:Frame
List all frames for the current window
Example
var frames = b.listAllFrames();
console.log(JSON.stringify(frames));
- See also
- module:Browser#listFrames
- Returns
Array of module:Frame
A nested array of frames
listCookies() → Array of module:Cookie
List all cookies set in the browser
- Returns
Array of module:Cookie
array of cookies
listDevices()
List devices available for emulation
Example
b = pizza.open();
b.listDevices();
listFrames([selector]) → Array of module:Frame
List the sub-frames for the currently selected frame.
See selectFrame() for details on the selector.
Example
var frames = b.listFrames();
console.log(JSON.stringify(frames));
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
Yes |
list any frames matching this selector |
- See also
- module:Browser#listAllFrames
- Returns
Array of module:Frame
An array of frames
listNetworkConditions()
List network conditions available for emulation
Example
b = pizza.open();
b.listNetworkConditions();
listTabs() → Array of module:Tab
List all tabs/windows open in browser
- Returns
Array of module:Tab
array of tabs
newPage([pageName]) → module:Page
Starts a new page object.
This allows you to name the page. HTTP requests made by the browser are added to this new page object. Page names show up in the script/test result page.
This function is useful to split out XHR or Ajax requests into a separate page which can be useful for reporting. With dynamic or single page apps, often user actions don't result in a page navigation, only background HTTP requests. In these cases you can use this function to split of the timings of various actions from each other and from the main page loading.
If no page navigation occurs the page load time is the total time HTTP content was downloaded. That is, the time span from the first item to start downloading until the last item on that page is fully downloaded.
Examples
b.open("www.mysite.com");
// Name a page, before submitting form
b.newPage("Submit form");
b.click("#submitButton");
b.waitPageLoad();
// Name a page, before opening
var b = pizza.open();
b.newPage("Bing Main Page");
b.open("bing.com");
Parameter
Name | Type | Optional | Description |
---|---|---|---|
pageName |
String |
Yes |
the name of the new page |
- Returns
the page that was navigated to.
newTab() → module:Tab
Open a new tab
- Returns
info about the selected tab.
open(url) → module:Page
Open the given URL
Function blocks until the page is open.
An exception is thrown if the navigation fails.
4xx and 5xx responses on the main document trigger a failure.
Example
var b = pizza.open();
b.open("www.google.com");
Parameter
Name | Type | Optional | Description |
---|---|---|---|
url |
String |
|
the url to open |
- See also
- module:Browser#ignoreHttpErrors
- module:Browser#openAsync
- Throws
Throws an exception when a 4xx or 5xx status code is returned for main document.
- Returns
a new page object for the given page.
openAsync(url)
Open the given URL
Does not wait for the page to load.
Normally you would call this in conjunction with waitForHttpRequests() or waitPageLoad()
Example
var b = pizza.open();
b.open("www.google.com");
b.waitVisible("input[name='q']");
Parameter
Name | Type | Optional | Description |
---|---|---|---|
url |
String |
|
the url to open |
query(selector) → Array of Element
Find the elements matching the given selector in the current frame.
Does not throw an exception if the selector is not matched. Instead an empty array is returned.
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
the elements to query |
- Returns
Array of Element
an array containing info about each of the elements that matched the selector
queryVisible(selector) → Array of Element
Find the elements matching the given selector in the current frame.
Does not throw an exception if the selector is not matched. Instead an empty array is returned.
Returns only visible elements.
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
The elements to query |
- Returns
Array of Element
An array containing info about each of the elements that matched the selector
reload()
Reload the current page.
4xx and 5xx responses on the main document trigger a failure after the page has loaded.
- See also
- module:Browser#ignoreHttpErrors
- Throws
Throws an exception when a 4xx or 5xx status code is returned for main document.
removeCookie(name)
Remove a given cookie from the browser for the current domain
Parameter
Name | Type | Optional | Description |
---|---|---|---|
name |
String |
|
the name of the cookie to remove |
removeCookie(url, name)
Remove a given cookie from the browser
Parameters
Name | Type | Optional | Description |
---|---|---|---|
url |
String |
|
the domain of the cookie to remove |
name |
String |
|
the name of the cookie to remove |
removeHeader(header)
Remove a given header
Removes a header that was previous added/overridden
Overridden headers are no longer overridden and the original header is still sent.
Example
var b = pizza.open();
// Load the site with the header set
b.setHeader('my-custom-header', 'this is the header');
b.open("mysite.com");
// Load the site without the header set
b.removeHeader('my-custom-header';
b.open("mysite.com");
Parameter
Name | Type | Optional | Description |
---|---|---|---|
header |
String |
|
The header to remove |
rewriteUrl(url, rewriteUrl)
Rewrite requests to the given URL
Accepts wildcards in the URL, but the URL must be of the form:
"protocol://host/path"
The protocol, site and path parts can wildcarded partially or fully.
Match groups are supported, just put parenthesis around each group. In the rewriteUrl string, match groups can be referred to via $1, $2, $3, etc.
Example
var b = pizza.open();
// Replace 'mario.jpg' with 'wario.jpg'
b.rewriteUrl('(*://www.mysite.com/*)/mario.jpg', '$1/wario.jpg');
b.open("www.mysite.com");
Parameters
Name | Type | Optional | Description |
---|---|---|---|
url |
String |
|
The wildcarded URL to match, can use match groups. |
rewriteUrl |
String |
|
The rewrite rule with match groups. |
- See also
- module:Browser#clearRules
screenshot([format][, quality])
Take a screenshot.
The format can be any of 'webp', 'png' or 'jpeg'.
If on a high DPI display, the screenshot is scaled down by the devicePixelRatio.
Example
var d = b.screenshot();
Parameters
Name | Type | Optional | Description |
---|---|---|---|
format |
String |
Yes |
The format of the image. Can be any of 'webp', 'png' or 'jpeg'. Defaults to |
quality |
Number |
Yes |
The quality of the image. 0.0 is least and smallest size, 1.0 is best quality and largest image size. Defaults to |
select(selector, value)
Select the given item/items of a dropdown or combobox
Examples
// Select by index
select("#toppings", {index: 1})
// Select by value
select("#toppings", {value: "option1"})
// Select by option text:
select("#topping", "Onions");
// This is the same as:
select("#toppings", {text: "Onions"})
// Select by option text matching Regex
select("#toppings", {match: ".nions"})
// Select multiple
select("#toppings", {value: ["option1", "option2"]})
select("#toppings", {text: ["Onions", "Pepperoni"})
select("#toppings", {match: [".nions", ".epperoni"})
select("#toppings", {index: [2, 3})
// Select multiple (but don't clear previous selection)
select("#toppings", {value: ["option1", "option2"], clear: false})
select("#toppings", {text: ["Onions", "Pepperoni"], clear: false})
select("#toppings", {match: [".nions", ".epperoni"], clear: false})
select("#toppings", {index: [2, 3], clear: false})
Parameters
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
the select element to select from |
value |
Select |
|
the values to select |
- Throws
Throws an exception if the element can not be found
selectContent(selector)
Select the content of the given element
Right now, basically only useful in combination with type() as an alternative to clear().
Example
// Clear the text in an input element with id 'id1'
b.selectContent("#input1");
b.type("#input1", Key.Backspace);
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
the element to select |
- Throws
Throws an exception if the element can not be found
selectFrame(selector) → module:Frame
Select the given frame using a special frame selector.
An extended/modified css syntax is used. The :nth operator can be used to select the nth element. For example, b.selectFrame("iframe:nth(1)") will select the the second iframe in the document. Spaces are used to select nested frames. Normally a CSS Selector won't traverse sub frames, but this function will. For example b.selectFrame("iframe iframe") will select the first iframe within an iframe. Once a frame is selected new calls to selectFrame() operate on the previously selected frame. To switch back to the main/top frame for the page call selectTopFrame().
An exception is thrown if no frame matching the selector can be found.
Examples
// Select the first iframe
b.selectFrame("iframe");
// Select the second iframe
b.selectFrame("iframe:nth(2)");
// Select the second iframe within the first iframe
b.selectFrame("iframe iframe:nth(2)");
// OR: you can make two calls to get the same result:
b.selectFrame("iframe");
b.selectFrame("iframe:nth(2)");
// Select iframe with the name 'name1'
b.selectFrame("iframe[name='name1']");
// Select iframe with the name 'name1'
b.selectFrame("iframe[name='name1']");
// Select iframe with src starting with 'dialog'
b.selectFrame("iframe[src^='/dialog']")
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
select the first frame matching this selector |
- Throws
Throws an exception if no frame matching the selector can be found.
- Returns
Details about the frame selected.
selectFrameCss(selector) → module:Frame
Select the given frame using a normal CSS Selector. None of the special syntax allowed by selectFrame() is used.
An exception is thrown if no frame matching the selector can be found.
Examples
// Select the first iframe
b.selectFrameCss("iframe");
// Select the iframe with the name 'name1'
b.selectFrameCss("iframe[name='name1']");
// Select iframe with src starting with 'dialog'
b.selectFrame("iframe[src^='/dialog']")
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
select the first frame matching this selector |
- Returns
Details about the frame selected.
selectLatestTab() → module:Tab
Select the most recently opened new tab.
- Returns
info about the selected tab
selectMainTab() → module:Tab
Select the main tab.
Select the main tab, this is the first tab opened, if the first tab was closed the oldest tab still around is select.
- Returns
info about the selected tab.
selectTab(obj) → module:Tab
Select the given tab
Examples
// By partial URL
selectTab({url: 'url'});
// By full URL
selectTab({url: 'url', full=true});
// By regex URL
selectTab({url: 'regex', regex=true});
// By partial title
selectTab({title: 'title'});
// By full title
selectTab({title: 'title', full=true});
// By regex title
selectTab({title: 'regex', regex=true});
// By Index (1st tab starts at 0)
selectTab({index: 0});
Parameter
Name | Type | Optional | Description |
---|---|---|---|
obj |
Object |
|
the tab selector |
- Returns
info about the selected tab
selectTopFrame() → module:Frame
Select the top level/main frame for the current window.
Example
// Switch to subframe
b.selectFrame("iframe iframe");
// Do stuff in the subframe
...
// Switch back to the top frame
b.selectTopFrame();
- Returns
The frame selected
setAuth(username, password)
Set the browser credentials.
These will be automatically entered whenever a credentials dialog would normally show up. Works with Basic Auth and all other forms of HTTP authentication supported by Chrome.
Example
// Open with a page with the credentials already set
var b = pizza.open();
b.setAuth('username', 'password');
b.open("www.mysite.com");
Parameters
Name | Type | Optional | Description |
---|---|---|---|
username |
String |
|
The username |
password |
String |
|
The password |
setCookie(name, value[, details])
Set a cookie
Set a cookie with the given name/value for the current domain.
Optional info can be given such as the expiry and the url.
Examples
// Set a cookie for the 'www.google.com' domain
b.setCookie("a", "b", { url: "http://www.google.com" })
// Load the site, then fake a login cookie
var b = pizza.open("www.mysite.com/");
b.setCookie("loginCreds", "dj431g5hgk");
b.open("www.mysite.com/");
Parameters
Name | Type | Optional | Description |
---|---|---|---|
name |
String |
|
the name of the cookie to be set, can a new name or and existing |
value |
String |
|
the value of the cookie to set |
details |
Yes |
optional extra info such as the expiry and the domain |
setFile(selector, file)
Set the file on a file input element.
The file path can be relative, or absolute (when the script is not sandboxed).
Example
b.setFile('#fileInput', 'file.png');
Parameters
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
the select element to select from |
file |
String |
|
the file path of the file to uploaded |
- Throws
Throws an exception if either the element or file can not be found
setHeader(name, value)
Override/Add a header
Examples
// Add a custom header
var b = pizza.open();
b.setHeader('my-custom-header', 'this is the header');
b.open("mysite.com");
// Overwrite an existing header
var b = pizza.open();
b.setHeader('Host', 'mysite2.com');
b.open("mysite.com");
Parameters
Name | Type | Optional | Description |
---|---|---|---|
name |
String |
|
The name of the header to set/override |
value |
String |
|
The value to set for the header |
setUserAgent(userAgent)
Set the user agent to something else.
Set to an empty string to set back to the default.
Sets both the HTTP request headers and the JavaScript navigator.userAgent
Example
var b = pizza.open();
// Pretend to be Internet Explorer 11.
b.setUserAgent('Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko');
b.open("www.mysite.com");
Parameter
Name | Type | Optional | Description |
---|---|---|---|
userAgent |
String |
|
The user agent to set |
setValue(selector, value)
Set the given input form element value.
Directly sets the value without causing any input events to be fired.
Example
b.setValue('input#textbox1', 'something');
Parameters
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
the selector to find the input element |
value |
String |
|
the value to set |
- Throws
Throws an exception if the element can not be found
startVideoCapture()
Start a video capture.
Starts a video capture if one is not already started. A video capture will normally be started as soon as Browser.protoype.open() is called.
Can be used to resume a stopped video recording.
stopVideoCapture()
Stops a video capture.
Stop an ongoing video capture.
- See also
- module:Browser#startVideoCapture
stopVideoCapture(name)
Emulate the given network condition.
Examples
// Open "bbc.com" emulating 3G latency and bandwidth constraints
b = pizza.open();
b.emulateNetworkCondition("Regular 3G");
b.open("bbc.com");
// Open "bbc.com" emulating a network latency of 50 milliseconds
b = pizza.open();
b.emulateNetworkCondition({latency: 50});
b.open("bbc.com");
// Disable a previously set network condition
b.emulateNetworkCondition({});
b.open("bbc.com");
Parameter
Name | Type | Optional | Description |
---|---|---|---|
name |
(String or Object) |
|
The network condition to emulate. Set to {} to disable network condition emulation. |
submit(selector)
Submit a form
The selector can point to any element in the form as well as the form itself.
This calls .submit() on the form, if this fails you can also try click() or type() on the submit button element.
Example
// Submit a form
b.submit('#form1');
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
the form element to submit |
- Throws
Throws an exception if the element can not be found
type(selector, ...text)
Type the given text into the first item matching the given selector
First it focuses the element (blurring the previously focused element), then it emulates key presses for the given text.
Examples
// Type the text 'Hello' into a text input with id 'id1'
b.type("#id1", "Hello");
// Type Pizza and then press enter, submitting the form.
b.type("#search", "Pizza\n");
// Type Pizza and then press tab, moving focus to next input element
b.type("#search", "Pizza\t");
// Can also send shortcuts (This only works to web elements, not
// the browser and certain system shortcuts like copy and paste
// are disabled).
b.type("#search", [Key.Control, Key.K]);
Parameters
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
the element to type text into |
text |
String |
|
the text to type Value can be repeated. |
verifyExists(selector)
Verify an element matching the given selector exists in the current frame/tab.
An exception is thrown if the element does not exist.
Example
// Verify that the given element exists on the page
b.verifyExists('#button1');
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
the element to verify |
- Throws
Throws an exception if the element can not be found
verifyNotExists(selector)
Verify no element matches the given selector exists in the current frame/tab.
An exception is thrown if the element exists.
Example
// Verify that the given element does not exist on the page
b.verifyNotExists('#errorDiv');
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
the element to verify |
- Throws
Throws an exception if the element is found
verifyNotText(text)
Verify that the text of the page does not contain the given string.
An exception is thrown if the given string exists on the page.
NOTE: Checks all frames.
Examples
b.verifyNotText("Error");
b.verifyNotText(/Error \d+:/);
Parameter
Name | Type | Optional | Description |
---|---|---|---|
text |
(String or RegExp) |
|
The text to look for on the page |
- See also
- module:Browser#hasText
- module:Browser#verifyText
- module:Browser#waitText
- module:Browser#getInnerText
verifyRequest(url)
Verify a request was made and had no errors on the current page.
An exception is thrown in the following cases:
- The request was never made / not found on the current page
- The request had an network/transport error
- The request has not completed yet
- The request had a HTTP status error code (4xx or 5xx status code)
WebSocket requests do not need to complete (i.e. be closed), but an error will thrown if the WebSocket did not successfully connect.
Examples
// Verify that a websocket connection was made
b.verifyRequest(/^ws{1,2}:/);
b.verifyRequest("https://loadtestgo.com");
Parameter
Name | Type | Optional | Description |
---|---|---|---|
url |
(String or RegExp) |
|
The request URL to check for. |
- Throws
Throws an exception if the request is not found or has an error.
verifyText(text)
Verify the given text exists on the current page.
Checks all frames.
An exception is thrown if the text does not exist.
Examples
b.verifyText("Sign in");
b.verifyText(/Hello, \w+/);
Parameter
Name | Type | Optional | Description |
---|---|---|---|
text |
(String or RegExp) |
|
verifyTitle(title)
Verify the page title matches the given title.
An exception is thrown if no text matches the title.
Examples
b.verifyTitle("Google");
// Matches Goooogle
b.verifyTitle(/Goo+gle/);
Parameter
Name | Type | Optional | Description |
---|---|---|---|
title |
(String or RegExp) |
|
The title to match |
- See also
- module:Browser#getTitle
waitElement(selector)
Wait for the given selector to be matched.
Example
// Wait for an element to exist in the DOM
b.waitElement('#divNew');
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
The element(s) to wait for |
waitElementText(selector, text)
Wait for the element matching the given selector to contain the given text.
The element does not need to exist at the time you called this function.
NOTE: Since a selector is specified, this only applies to the currently selected frame.
Example
b.waitElementText("#consoleLog", "DISCONNECTED");
Parameters
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
the element to wait for |
text |
String |
|
the text to wait for |
- See also
- module:Browser#waitText
- module:Browser#hasText
- module:Browser#verifyText
- module:Browser#verifyNotText
waitForHttpRequests(idleTimeMS)
Wait for all ongoing HTTP requests to stop.
idleTimeMS is the minimum time to wait, this function will not return before then.
Waits for Web Socket connections to fully open if there is one ongoing, but does not wait for idle time on the WebSocket connection or for it to close.
Example
var b = pizza.open("www.facebook.com");
b.waitForHttpRequests(2000);
Parameter
Name | Type | Optional | Description |
---|---|---|---|
idleTimeMS |
Number |
|
the time to wait after the last request has completed |
waitNotText(text)
Wait for the current window / tab to not contain the given text.
Example
b.waitNotText("Sign In");
Parameter
Name | Type | Optional | Description |
---|---|---|---|
text |
String |
|
the text to not wait for |
- See also
- module:Browser#waitText
- module:Browser#hasText
- module:Browser#verifyText
- module:Browser#verifyNotText
- module:Browser#getInnerText
waitNotVisible(selector)
Wait for the given selector to either not be matched or matched but none of the resulting elements are visible. Checks current frame only.
NOTE: The element does not need to be visible to begin with.
Example
// The #errorDiv to be removed / hidden from DOM.
b.waitNotVisible('#errorDiv');
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
The element(s) to wait for to be no longer visible |
waitPageLoad([timeoutMS]) → module:Page
Wait for a new page to load on the current tab.
If a page is recently loaded, and that page was not waited on before (either by open() or this function), then the function will just return. If the page opens in a new tab or window be sure to switch to that tab or window before calling waitPageLoad().
HTTP redirects are waited on too. So one call on waitPageLoad() will wait on the page redirects and the main redirected page to be loaded.
4xx and 5xx responses on the main document trigger a failure.
Example
b.click("#button1");
b.waitPageLoad();
Parameter
Name | Type | Optional | Description |
---|---|---|---|
timeoutMS |
Number |
Yes |
the max time to wait in milliseconds |
- See also
- module:Browser#openAsync
- module:Browser#click
- Throws
Throws an exception when a 4xx or 5xx status code is returned for main document.
- Returns
the page that was navigated to.
waitText(text)
Wait for the current window / tab to contain the given text.
Example
b.waitText("Sign Out");
Parameter
Name | Type | Optional | Description |
---|---|---|---|
text |
String |
|
the text to wait for |
- See also
- module:Browser#waitNotText
- module:Browser#hasText
- module:Browser#verifyText
- module:Browser#verifyNotText
- module:Browser#getInnerText
waitVisible(selector)
Wait for the given selector to be matched and at least one resulting element to be visible.
Checks current frame only.
Example
// Wait for an element to be visible
b.waitVisible('#button1');
Parameter
Name | Type | Optional | Description |
---|---|---|---|
selector |
String |
|
The element(s) to wait for |