The Accessibility class provides methods for inspecting Chromium's accessibility tree. The accessibility tree is used by assistive technology such as screen readers or switches.
Accessibility is a very platform-specific thing. On different platforms, there are different screen readers that might have wildly different output.
Blink - Chrome's rendering engine - has a concept of "accessibility tree", which is than translated into different platform-specific APIs. Accessibility namespace gives users access to the Blink Accessibility Tree.
Most of the accessibility tree gets filtered out when converting from Blink AX Tree to Platform-specific AX-Tree or by assistive technologies themselves. By default, Puppeteer tries to approximate this filtering, exposing only the "interesting" nodes of the tree.
see Accessibility for more details
helpers to troubleshoot automation issues.
see Diagnostics for more information
automate keyboard presses.
see Keyboard for more information
contains helpers for operating beyond the current page. such as get/set values between page navigations, and logging details that will be stored in your response output.
See the Meta documentation for more details.
contains functions for controlling the mouse on the page. Clicking, moving, etc. Also see Touchscreen and Keyboard.
See the Mouse documentation for more details.
The page.on() allows you to attach to events of the page.
For example:
page.on('load', () => page.meta.log('Page loaded!'));
For details of all events you can hook, please see PageOnEvents
For syntax and details of all events you can hook, please see PageOnEvents
For syntax and details of all events you can hook, please see PageOnEvents
automate taps on a touch screen.
See Touchscreen for more information
perform performance traces.
Runs document.querySelector in the main frame and returns the first matching element as an :class,
or null when nothing matches.
Like the other main-frame calls, it waits until pjsc's own navigation to the request url has finished.
const button = await page.$("#submit");
if (button) await button.click();
a CSS selector
Runs document.querySelectorAll in the main frame and returns every matching element as an :class
(an empty array when nothing matches).
const rows = await page.$$("table tr");
page.meta.log("rows", rows.length);
a CSS selector
selector <string> A selector to query page forpageFunction <function(Array<Element<)< Function to be evaluated in browser contextargs <...Serializable|JSHandle< Arguments to pass to pageFunctionThis method runs Array.from(document.querySelectorAll(selector)) within the page and passes it as the first argument to pageFunction.
If pageFunction returns a Promise, then page.$$eval would wait for the promise to resolve and return its value.
Examples:
const divsCounts = await page.$$eval('div', divs => divs.length);
selector <string> A selector to query page forpageFunction <function(Array<Element<)< Function to be evaluated in browser contextargs <...Serializable|JSHandle< Arguments to pass to pageFunctionThis method runs Array.from(document.querySelectorAll(selector)) within the page and passes it as the first argument to pageFunction.
If pageFunction returns a Promise, then page.$$eval would wait for the promise to resolve and return its value.
Examples:
const divsCounts = await page.$$eval('div', divs => divs.length);
selector <string> A selector to query page forpageFunction <function(Element)> Function to be evaluated in browser contextargs <...Serializable|JSHandle> Arguments to pass to pageFunctionThis method runs document.querySelector within the page and passes it as the first argument to pageFunction. If there's no element matching selector, the method throws an error.
If pageFunction returns a Promise, then page.$eval would wait for the promise to resolve and return its value.
Examples:
const searchValue = await page.$eval('#search', el => el.value);
const preloadHref = await page.$eval('link[rel=preload]', el => el.href);
const html = await page.$eval('.main-container', e => e.outerHTML);
selector <string> A selector to query page forpageFunction <function(Element)> Function to be evaluated in browser contextargs <...Serializable|JSHandle> Arguments to pass to pageFunctionThis method runs document.querySelector within the page and passes it as the first argument to pageFunction. If there's no element matching selector, the method throws an error.
If pageFunction returns a Promise, then page.$eval would wait for the promise to resolve and return its value.
Examples:
const searchValue = await page.$eval('#search', el => el.value);
const preloadHref = await page.$eval('link[rel=preload]', el => el.href);
const html = await page.$eval('.main-container', e => e.outerHTML);
options <Object>
- url <string> URL of a script to be added.
- content <string> Raw JavaScript content to be injected into frame.
- type <string> Script type. Use 'module' in order to load a Javascript ES6 module. See script for more details.Adds a <script> tag into the page with the desired url or content.
options <Object>
- url <string> URL of the <link< tag.
- content <string> Raw CSS content to be injected into frame.Adds a <link rel="stylesheet" > tag into the page with the desired url or a <style type="text/css"> tag with the content.
credentialOptions <?Object<
- username <string>
- password <string>Provide credentials for HTTP authentication. On a render whose proxy has a login (pjsc's built-in proxy, the geo proxy,
or a custom proxy with auth), they answer only the website's login prompts and the proxy's login stays; on other
renders they answer every login prompt, as in Puppeteer.
To clear the credentials, pass null.
Brings page to front (activates tab).
selector <string> A selector to search for element to click. If there are multiple elements satisfying the selector, the first will be clicked.options <Object>
- button <"left"|"right"|"middle"< Defaults to left.
- clickCount <number> defaults to 1. See UIEvent.detail.
- delay <number> Time to wait between mousedown and mouseup in milliseconds. Defaults to 0.This method fetches an element with selector, scrolls it into view if needed, and then uses page.mouse to click in the center of the element. If there's no element matching selector, the method throws an error.
Bear in mind that if click() triggers a navigation event and there's a separate page.waitForNavigation() promise to be resolved, you may end up with a race condition that yields unexpected results. The correct pattern for click and wait for navigation is the following:
const [response] = await Promise.all([
page.waitForNavigation(waitOptions),
page.click(selector, clickOptions),
]);
Optionaloptions: ClickOptions & FrameExecOptionsVery similar to Render.content but instead of storing the html/text to output, it is returned by this function.
a string containing html/plainText.
urls <...string>name <string>
- value <string>
- domain <string>
- path <string>
- expires <number> Unix time in seconds.
- size <number>
- httpOnly <boolean>
- secure <boolean>
- session <boolean>
- sameSite <"Strict"|"Lax"|"Extended"|"None">If no URLs are specified, this method returns cookies for the current page URL. If URLs are specified, only cookies for those URLs are returned.
cookies <...Object>
- name <string> required
- url <string>
- domain <string>
- path <string>call this to signal that your request is done and the results can be returned to you. Especially useful in conjunction with Page.manualWait but can also be used to finish execution earlier than normal (not wait for ajax scripts, etc).
allows you to customize the value of content.statusCode in the output JSON and response headers.
Note: this does not change the API's response code. It lets you customize a "content" code when parsing the results.
allows you to customize the value of content.doneDetail in the output JSON and response headers
options <Object>
- viewport <Object>
- width <number> page width in pixels.
- height <number> page height in pixels.
- deviceScaleFactor <number> Specify device scale factor (can be thought of as dpr). Defaults to 1.
- isMobile <boolean> Whether the meta viewport tag is taken into account. Defaults to false.
- hasTouch<boolean> Specifies if viewport supports touch events. Defaults to false
- isLandscape <boolean> Specifies if viewport is in landscape mode. Defaults to false.
- userAgent <string>Emulates given device metrics and user agent. This method is a shortcut for calling two methods:
page.setUserAgent(userAgent)
page.setViewport(viewport)
NOTE: page.emulate will resize the page. A lot of websites don't expect phones to change size, so you should emulate before navigating to the page.
Slows the page's CPU by factor (1 = no throttling); null ends the throttling.
slowdown factor, at least 1
Makes the page behave as if it had focus (document.hasFocus(), focus events), or ends that emulation.
true emulates a focused page
Emulates the user idle state; no argument ends the emulation.
Optionaloverrides: { isScreenUnlocked: boolean; isUserActive: boolean }
isUserActive, isScreenUnlocked
use Page.emulateMediaType instead
Given an array of media feature objects, emulates CSS media features on the page. Passing null resets all.
await page.emulateMediaFeatures([{ name: 'prefers-color-scheme', value: 'dark' }]);
await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches));
// → true
await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches));
// → false
await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').matches));
// → false
await page.emulateMediaFeatures([{ name: 'prefers-reduced-motion', value: 'reduce' }]);
await page.evaluate(() => matchMedia('(prefers-reduced-motion: reduce)').matches));
// → true
await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').matches));
// → false
await page.emulateMediaFeatures([
{ name: 'prefers-color-scheme', value: 'dark' },
{ name: 'prefers-reduced-motion', value: 'reduce' },
]);
await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches));
// → true
await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches));
// → false
await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').matches));
// → false
await page.evaluate(() => matchMedia('(prefers-reduced-motion: reduce)').matches));
// → true
await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').matches));
// → false
mediaType <?string> Changes the CSS media type of the page. The only allowed values are 'screen', 'print' and null. Passing null disables media emulation.Emulates network conditions (download/upload throughput in bytes per second, latency in milliseconds); null ends the
emulation.
Simulates a vision deficiency on the rendered page.
Optionaltype: "none", "achromatopsia", "blurredVision", "deuteranopia", "protanopia", "tritanopia" or
"reducedContrast"
pageFunction <function|string> Function to be evaluated in the page contextargs <...Serializable|JSHandle> Arguments to pass to pageFunctionIf the function passed to the page.evaluate returns a Promise, then page.evaluate would wait for the promise to resolve and return its value.
If the function passed to the page.evaluate returns a non-Serializable value, then page.evaluate resolves to undefined. DevTools Protocol also supports transferring some additional values that are not serializable by JSON: -0, NaN, Infinity, -Infinity, and bigint literals.
Here is an example request JSON that returns true if the body tag exists.
{
url: "https://example.com",
renderType: "automation",
overseerScript:'await page.waitForNavigation(); var exists = await page.evaluate(()=>{ return document.getElementsByTagName("body").length >0 }); if(exists!=null){page.meta.store.set("key",exists);} ',
}
Passing arguments to pageFunction:
//overseerScript code
const result = await page.evaluate(x => {
return Bluebird.Promise.resolve(8 * x);
}, 7);
console.log(result); // prints "56"
A string can also be passed in instead of a function:
//overseerScript code
console.log(await page.evaluate('1 + 2')); // prints "3"
const x = 10;
console.log(await page.evaluate(`1 + ${x}`)); // prints "11"
Arguments must be JSON values or handles: an element of your script's own page passed as an argument arrives as undefined.
A handle (Page.$, Page.$$, Page.evaluateHandle) is accepted as an argument; with one and no
selectFrame, the call runs in the main frame only.
pageFunction <function|string> Function to be evaluated in the page contextargs <...Serializable|JSHandle> Arguments to pass to pageFunctionIf the function passed to the page.evaluate returns a Promise, then page.evaluate would wait for the promise to resolve and return its value.
If the function passed to the page.evaluate returns a non-Serializable value, then page.evaluate resolves to undefined. DevTools Protocol also supports transferring some additional values that are not serializable by JSON: -0, NaN, Infinity, -Infinity, and bigint literals.
Here is an example request JSON that returns true if the body tag exists.
{
url: "https://example.com",
renderType: "automation",
overseerScript:'await page.waitForNavigation(); var exists = await page.evaluate(()=>{ return document.getElementsByTagName("body").length >0 }); if(exists!=null){page.meta.store.set("key",exists);} ',
}
Passing arguments to pageFunction:
//overseerScript code
const result = await page.evaluate(x => {
return Bluebird.Promise.resolve(8 * x);
}, 7);
console.log(result); // prints "56"
A string can also be passed in instead of a function:
//overseerScript code
console.log(await page.evaluate('1 + 2')); // prints "3"
const x = 10;
console.log(await page.evaluate(`1 + ${x}`)); // prints "11"
Arguments must be JSON values or handles: an element of your script's own page passed as an argument arrives as undefined.
A handle (Page.$, Page.$$, Page.evaluateHandle) is accepted as an argument; with one and no
selectFrame, the call runs in the main frame only.
Runs pageFunction in the main frame and returns its result as a :class (an :class
when the result is a DOM element), instead of copying the result as JSON like Page.evaluate.
const body = await page.evaluateHandle(() => document.body);
const html = await body.evaluate((b) => b.innerHTML.length);
function (or its source text) run inside the page
JSON values or handles passed to pageFunction
pageFunction <function|string> Function to be evaluated in browser contextargs <...Serializable> Arguments to pass to pageFunctionAdds a function which would be invoked in one of the following scenarios:
The function is invoked after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed Math.random.
An example of overriding the navigator.languages property before the page loads:
overseerScript:'await page.evaluateOnNewDocument(() => {Object.defineProperty(navigator, "language", {get: function() {return ["de-DE","de"];}});Object.defineProperty(navigator, "languages", {get: function() {return ["de-DE", "de"];}});});',
Adds a function window[name] to the page (every frame, also after navigations). When the page calls it, your function
runs in your overseer script and the page receives its result as a promise.
pjsc differences:
print, showDirectoryPicker, showOpenFilePicker and showSaveFilePicker are pjsc's own and cannot be exposed or
removed; a name that is already exposed must be removed first with Page.removeExposedFunction.await page.exposeFunction("report", (value) => page.meta.log("from page", value));
await page.evaluate(() => window.report(document.title));
the window property name
the function, or { default: function }
selector <string> A selector of an element to focus. If there are multiple elements satisfying the selector, the first will be focused.This method fetches an element with selector and focuses it. If there's no element matching selector, the method throws an error.
Optionaloptions: FrameExecOptionsAll frames of the page as :class objects, the main frame first. Synchronous: the list is kept current as frames attach, detach and navigate.
Page.mainFrame returns a frame summary ({url, name, guid}); use page.frames()[0] for the main frame's
:class object.
for (const frame of page.frames()) page.meta.log(frame.url());
The page's default navigation timeout in milliseconds (Page.setDefaultNavigationTimeout).
The page's default timeout in milliseconds for waits (Page.setDefaultTimeout).
options <Object> Navigation parameters which might have the following properties:
- timeout <number> Maximum navigation time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the page.setDefaultNavigationTimeout(timeout) or page.setDefaultTimeout(timeout) methods.
- waitUntil <string|Array<string>> When to consider navigation succeeded, defaults to load. Given an array of event strings, navigation is considered to be successful after all events have been fired. Events can be either:
- load - consider navigation to be finished when the load event is fired.
- domcontentloaded - consider navigation to be finished when the DOMContentLoaded event is fired.
- networkidle0 - consider navigation to be finished when there are no more than 0 network connections for at least 500 ms.
- networkidle2 - consider navigation to be finished when there are no more than 2 network connections for at least 500 ms.Navigate to the previous page in history.
options <Object> Navigation parameters which might have the following properties:
- timeout <number> Maximum navigation time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the page.setDefaultNavigationTimeout(timeout) or page.setDefaultTimeout(timeout) methods.
- waitUntil <string|Array<<string>> When to consider navigation succeeded, defaults to load. Given an array of event strings, navigation is considered to be successful after all events have been fired. Events can be either:
- load - consider navigation to be finished when the load event is fired.
- domcontentloaded - consider navigation to be finished when the DOMContentLoaded event is fired.
- networkidle0 - consider navigation to be finished when there are no more than 0 network connections for at least 500 ms.
- networkidle2 - consider navigation to be finished when there are no more than 2 network connections for at least 500 ms.Navigate to the next page in history.
url <string> URL to navigate page to. The url should include scheme, e.g. https://.options <Object> Navigation parameters which might have the following properties:
- timeout <number> Maximum navigation time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the page.setDefaultNavigationTimeout(timeout) or page.setDefaultTimeout(timeout) methods.
- waitUntil <string|Array<string>> When to consider navigation succeeded, defaults to load. Given an array of event strings, navigation is considered to be successful after all events have been fired. Events can be either:
- load - consider navigation to be finished when the load event is fired.
- domcontentloaded - consider navigation to be finished when the DOMContentLoaded event is fired.
- networkidle0 - consider navigation to be finished when there are no more than 0 network connections for at least 500 ms.
- networkidle2 - consider navigation to be finished when there are no more than 2 network connections for at least 500 ms.
- referer <string> Referer header value. If provided it will take preference over the referer header value set by page.setExtraHTTPHeaders().page.goto will throw an error if:
page.goto will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling response.status().
NOTE page.goto either throws an error or returns a main resource response. The only exceptions are navigation to about:blank or navigation to the same URL with a different hash, which would succeed and return null.
Optionaloptions: NavigationOptions & FrameExecOptionsselector <string> A selector to search for element to hover. If there are multiple elements satisfying the selector, the first will be hovered.options allows choosing a specific frame (main frame, or a child IFrame). defaults to searching all frames, stopping at the first successful execution.This method fetches an element with selector, scrolls it into view if needed, and then uses page.mouse to hover over the center of the element. If there's no element matching selector, the method throws an error.
Optionaloptions: FrameExecOptionsWhether the page is closed.
Whether drag interception is enabled (Page.setDragInterception).
Whether JavaScript is enabled on the page (Page.setJavaScriptEnabled).
Whether service workers are bypassed (Page.setBypassServiceWorker).
Creates a :class for selector in the main frame (synchronous; nothing runs until an action is called).
A locator waits for its element to be attached, visible, enabled and stable before it acts, and retries until its timeout.
await page.locator("button.accept").click();
await page.locator("#search").fill("phantomjscloud");
a CSS selector (puppeteer selector syntax), or a function (or its source text) run in the page whose truthy result the locator waits for
{url, name, guid}).Page is guaranteed to have a main frame which persists during navigations.
To act on the main frame (goto, evaluate, $, locator, ...) use its Frame:class object: page.frames()[0].
call this to signal the API to NOT complete when it thinks the page is done loading. Instead, it will complete only when you call Page.done
returns: <Promise<Object>> Object containing metrics as key/value pairs. - Timestamp <number> The timestamp when the metrics sample was taken. - Documents <number> Number of documents in the page. - Frames <number> Number of frames in the page. - JSEventListeners <number> Number of events in the page. - Nodes <number> Number of DOM nodes in the page. - LayoutCount <number> Total number of full or partial page layout. - RecalcStyleCount <number> Total number of page style recalculations. - LayoutDuration <number> Combined durations of all page layouts. - RecalcStyleDuration <number> Combined duration of all page style recalculations. - ScriptDuration <number> Combined duration of JavaScript execution. - TaskDuration <number> Combined duration of all tasks performed by the browser. - JSHeapUsedSize <number> Used JavaScript heap size. - JSHeapTotalSize <number> Total JavaScript heap size.
NOTE All timestamps are in monotonic time: monotonically increasing time in seconds since an arbitrary point in the past.
reloads the page. can pass navigation options.
Removes a function added with Page.exposeFunction.
the name given to Page.exposeFunction
Removes a script added with Page.evaluateOnNewDocument.
the identifier of the object Page.evaluateOnNewDocument returned
shortcut to Render.screenshot
Optionaloptions: Base64ScreenShotOptionsmanipulate a html select element.
selector <string> A selector to query page forvalues <...string> Values of options to select. If the <select< has the multiple attribute, all values are considered, otherwise only the first one is taken into account.Triggers a change and input event once all the provided options have been selected. If there's no <select< element matching selector, the method throws an error.
page.select('select#colors', 'blue'); // single selection
page.select('select#colors', 'red', 'green', 'blue'); // multiple selections
manipulate a html select element.
selector <string> A selector to query page forvalues <...string> Values of options to select. If the <select< has the multiple attribute, all values are considered, otherwise only the first one is taken into account.Triggers a change and input event once all the provided options have been selected. If there's no <select< element matching selector, the method throws an error.
page.select('select#colors', 'blue'); // single selection
page.select('select#colors', 'red', 'green', 'blue'); // multiple selections
Optionaloptions: FrameExecOptionsToggles bypassing the page's Content-Security-Policy. Takes effect at the next navigation.
true bypasses the policy
Toggles bypassing the page's service workers for its requests.
true bypasses service workers
Toggles the browser cache for the page's requests (enabled by default).
Optionalenabled: boolean
false disables the cache
html <string> HTML markup to assign to the page.options <Object> Parameters which might have the following properties:
- timeout <number> Maximum time in milliseconds for resources to load, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the page.setDefaultNavigationTimeout(timeout) or page.setDefaultTimeout(timeout) methods.
- waitUntil {string|Array{string>> When to consider setting markup succeeded, defaults to load. Given an array of event strings, setting content is considered to be successful after all events have been fired. Events can be either:
- load - consider setting content to be finished when the load event is fired.
- domcontentloaded - consider setting content to be finished when the DOMContentLoaded event is fired.
- networkidle0 - consider setting content to be finished when there are no more than 0 network connections for at least 500 ms.
- networkidle2 - consider setting content to be finished when there are no more than 2 network connections for at least 500 ms.Optionaloptions: NavigationOptions & FrameExecOptionscookies <...Object>
- name <string> required
- value <string> required
- url <string>
- domain <string>
- path <string>
- expires <number> Unix time in seconds.
- httpOnly <boolean>
- secure <boolean>
- sameSite <"Strict"|"Lax">await page.setCookie(cookieObject1, cookieObject2);
This setting will change the default maximum navigation time for the following methods and related shortcuts:
page.setDefaultNavigationTimeout takes priority over page.setDefaultTimeoutdefault: 15000 (15 seconds)
This setting will change the default maximum time for the following methods and related shortcuts:
page.goBack([options])
page.goForward([options])
page.goto(url[, options])
page.reload([options])
page.setContent(html[, options])
page.waitFor(selectorOrFunctionOrTimeout[, options[, ...args]])
page.waitForFunction(pageFunction[, options[, ...args]])
page.waitForNavigation([options])
page.waitForRequest(urlOrPredicate[, options])
page.waitForResponse(urlOrPredicate[, options])
page.waitForSelector(selector[, options])
page.waitForXPath(xpath[, options])
NOTE page.setDefaultNavigationTimeout takes priority over page.setDefaultTimeout
Enables drag interception: Mouse.drag then returns the drag data instead of the browser starting a native drag, for use with Mouse.dragEnter, Mouse.dragOver and Mouse.drop.
true intercepts drags
The extra HTTP headers will be sent with every request the page initiates.
NOTE page.setExtraHTTPHeaders does not guarantee the order of headers in the outgoing requests.
Sets the page's geolocation.
await page.setGeolocation({latitude: 59.95, longitude: 30.31667});
Enables or disables JavaScript on the page. Takes effect at the next navigation.
false disables JavaScript
enabled <boolean> When true, enables offline mode for the page.Sets the user agent string the page sends with its requests and reports as navigator.userAgent.
userAgent <string> Specific user agent to use in this pageviewport <Object>
- width <number> page width in pixels. required
- height <number> page height in pixels. required
- deviceScaleFactor <number> Specify device scale factor (can be thought of as dpr). Defaults to 1.
- isMobile <boolean> Whether the meta viewport tag is taken into account. Defaults to false.
- hasTouch<boolean> Specifies if viewport supports touch events. Defaults to false
- isLandscape <boolean> Specifies if viewport is in landscape mode. Defaults to false.In the case of multiple pages in a single browser, each page can have its own viewport size.
page.setViewport will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport before navigating to the page.
await page.setViewport({
width: 640,
height: 480,
deviceScaleFactor: 1,
});
await page.goto('https://example.com');
selector <string> A selector to search for element to tap. If there are multiple elements satisfying the selector, the first will be tapped.This method fetches an element with selector, scrolls it into view if needed, and then uses page.touchscreen to tap in the center of the element. If there's no element matching selector, the method throws an error.
Optionaloptions: FrameExecOptionsOptionalframeGuid: stringselector <string> A selector of an element to type into. If there are multiple elements satisfying the selector, the first will be used.text <string> A text to type into a focused element.options <Object>
delay <number> Time to wait between key presses in milliseconds. Defaults to 0.Sends a keydown, keypress/input, and keyup event for each character in the text.
To press a special key, like Control or ArrowDown, use keyboard.press.
page.type('#mytextarea', 'Hello'); // Types instantly
page.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user
Optionaloptions: { delay: number } & FrameExecOptionsreturns a promise resolving to the url.
OptionalframeGuid: stringreads the page's current viewport.
returns: <?Object<
width <number> page width in pixels.height <number> page height in pixels.deviceScaleFactor <number> Specify device scale factor (can be though of as dpr). Defaults to 1.isMobile <boolean> Whether the meta viewport tag is taken into account. Defaults to false.hasTouch<boolean> Specifies if viewport supports touch events. Defaults to falseisLandscape <boolean> Specifies if viewport is in landscape mode. Defaults to false.waits for the given number of ms
returns if/when the current page domContentLoaded event is triggered
Waits for a frame whose url equals urlOrPredicate, or for which the predicate returns true, and returns it. The current
frames are checked first, then every frame change.
const frame = await page.waitForFrame((f) => f.url().includes("checkout"), { timeout: 10000 });
the exact frame url, or a function (frame) => boolean | Promise<boolean>
Optionaloptions: { timeout?: number }
timeout in milliseconds; defaults to the page's default timeout (30000 unless
Page.setDefaultTimeout changed it); 0 waits without limit. signal is not supported.
pageFunction <function|string> Function to be evaluated in browser contextoptions <Object> Optional waiting parameters
- polling <string|number< An interval at which the pageFunction is executed, defaults to raf. If polling is a number, then it is treated as an interval in milliseconds at which the function would be executed. If polling is a string, then it can be one of the following values:
- raf - to constantly execute pageFunction in requestAnimationFrame callback. This is the tightest polling mode which is suitable to observe styling changes.
- mutation - to execute pageFunction on every DOM mutation.
- timeout <number> maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the page.setDefaultTimeout(timeout) method.args <...Serializable|JSHandle> Arguments to pass to pageFunctionThe waitForFunction can be used to observe viewport size change:
const watchDog = page.waitForFunction('window.innerWidth < 100');
await page.setViewport({width: 50, height: 50});
await watchDog;
await page.done();
});
To pass arguments from node.js to the predicate of page.waitForFunction function:
const selector = '.foo';
await page.waitForFunction(selector => !!document.querySelector(selector), {}, selector);
Optionaloptions: PageFnOptions & FrameExecOptionsreturns if/when the current page load event is triggered
IMPORTANT This function will not complete until a page Navigation occurs. Thus if the page is already loaded, this function will stall until the next page load occurs.
So if you await a command that performs a navigation (eg: await page.click("input[type=button][value=Login]"); )
then if the next line calls await page.waitForNavigation() it will block until the api call times out. A workaround is to make sure you do not await the command that calls the navigation (the page.click() command).
This resolves when the page navigates to a new URL or reloads. It is useful for when you run code which will indirectly cause the page to navigate. Consider this example:
Optionaloptions: NavigationOptions & FrameExecOptionsWaits until the page's network is idle: at most concurrency requests in flight for idleTime milliseconds.
Like the other main-frame calls, it first waits until pjsc's own navigation to the request url has finished.
Optionaloptions: { concurrency?: number; idleTime?: number; timeout?: number }
idleTime (default 500 ms), timeout (default: the page's default timeout; 0 = no limit),
concurrency (default 0)
urlOrPredicate <string|function> The request url to wait for, or a predicate function. The predicate receives each
request as an HTTPRequest object (methods url(), method(), headers(), resourceType(), ...) and returns
(or resolves to) true for the request to wait for. A predicate that throws makes the wait fail.options <Object> Optional waiting parameters
- timeout <number> Maximum wait time in milliseconds, defaults to 30 seconds, pass 0 to disable the timeout.const req = await page.waitForRequest("https://example.com/api/data");
const post = await page.waitForRequest((r) => r.method() === "POST" && r.url().includes("/api/"));
page.meta.log(post.url, post.postData);
Optionaloptions: TimeoutableurlOrPredicate <string|function> The response url to wait for, or a predicate function. The predicate receives each
response as an HTTPResponse object (methods url(), status(), headers(), request(), ...) and returns
(or resolves to) true for the response to wait for. A predicate that throws makes the wait fail.options <Object> Optional waiting parameters
- timeout <number> Maximum wait time in milliseconds, defaults to 30 seconds, pass 0 to disable the timeout.const res = await page.waitForResponse((r) => r.url().endsWith("/api/data") && r.status() === 200);
page.meta.log(res.status, res.headers["content-type"]);
Optionaloptions: Timeoutableselector <string> A selector of an element to wait foroptions <Object> Optional waiting parameters
- visible <boolean> wait for element to be present in DOM and to be visible, i.e. to not have display: none or visibility: hidden CSS properties. Defaults to false.
- hidden <boolean> wait for element to not be found in the DOM or to be hidden, i.e. have display: none or visibility: hidden CSS properties. Defaults to false.
- timeout <number> maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the page.setDefaultTimeout(timeout) method.Wait for the selector to appear in page. If at the moment of calling the method the selector already exists, the method will return immediately. If the selector doesn't appear after the timeout milliseconds of waiting, the function will throw.
This method works across navigations:
let currentURL;
page
.waitForSelector('img')
.then(() => console.log('First URL with image: ' + currentURL));
for (currentURL of ['https://example.com', 'https://google.com', 'https://bbc.com'])
await page.goto(currentURL);
await page.done();
Optionaloptions: WaitForSelectorOptions & FrameExecOptionsxpath <string> A xpath of an element to wait foroptions <Object> Optional waiting parameters
- visible <boolean> wait for element to be present in DOM and to be visible, i.e. to not have display: none or visibility: hidden CSS properties. Defaults to false.
- hidden <boolean> wait for element to not be found in the DOM or to be hidden, i.e. have display: none or visibility: hidden CSS properties. Defaults to false.
- timeout <number> maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the page.setDefaultTimeout(timeout) method.Wait for the xpath to appear in page. If at the moment of calling the method the xpath already exists, the method will return immediately. If the xpath doesn't appear after the timeout milliseconds of waiting, the function will throw.
This method works across navigations:
let currentURL;
page
.waitForXPath('//img')
.then(() => console.log('First URL with image: ' + currentURL));
for (currentURL of ['https://example.com', 'https://google.com', 'https://bbc.com'])
await page.goto(currentURL);
await page.done();
Optionaloptions: WaitForSelectorOptions & FrameExecOptionsThis method returns all of the dedicated WebWorkers associated with the page.
Methods to interact with a single page (tab) in the Chrome browser.
This is usable globally from your script (no need to construct a new instance)
Example showing basic automaton: