Abstract
{@inheritDoc Accessibility}
Abstract
coverage{@inheritDoc Coverage}
Abstract
keyboard{@inheritDoc Keyboard}
Abstract
mouse{@inheritDoc Mouse}
Abstract
touchscreen{@inheritDoc Touchscreen}
Abstract
tracing{@inheritDoc Tracing}
Finds the first element that matches the selector. If no element matches
the selector, the return value resolves to null
.
selector to query page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Finds elements on the page that match the selector. If no elements
match the selector, the return value resolves to []
.
selector to query page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Optional
options: QueryOptionsThis method returns all elements matching the selector and passes the
resulting array as the first argument to the pageFunction
.
selector to query page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
the function to be evaluated in the page context. Will be passed an array of matching elements as its first argument.
Rest
...args: Paramsany additional arguments to pass through to pageFunction
.
The result of calling pageFunction
. If it returns an element it
is wrapped in an ElementHandle, else the raw value itself is
returned.
If pageFunction
returns a promise $$eval
will wait for the promise to
resolve and then return its value.
// get the amount of divs on the page
const divCount = await page.$$eval('div', divs => divs.length);
// get the text content of all the `.options` elements:
const options = await page.$$eval('div > span.options', options => {
return options.map(option => option.textContent);
});
If you are using TypeScript, you may have to provide an explicit type to the
first argument of the pageFunction
.
By default it is typed as Element[]
, but you may need to provide a more
specific sub-type:
await page.$$eval('input', elements => {
return elements.map(e => e.value);
});
The compiler should be able to infer the return type
from the pageFunction
you provide. If it is unable to, you can use the generic
type to tell the compiler what return type you expect from $$eval
:
const allInputValues = await page.$$eval('input', elements =>
elements.map(e => e.textContent)
);
This method finds the first element within the page that matches the selector
and passes the result as the first argument to the pageFunction
.
selector to query page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
the function to be evaluated in the page context. Will be passed the result of the element matching the selector as its first argument.
Rest
...args: Paramsany additional arguments to pass through to pageFunction
.
The result of calling pageFunction
. If it returns an element it
is wrapped in an ElementHandle, else the raw value itself is
returned.
If no element is found matching selector
, the method will throw an error.
If pageFunction
returns a promise $eval
will wait for the promise to
resolve and then return its value.
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', el => el.outerHTML);
If you are using TypeScript, you may have to provide an explicit type to the
first argument of the pageFunction
.
By default it is typed as Element
, but you may need to provide a more
specific sub-type:
// if you don't provide HTMLInputElement here, TS will error
// as `value` is not on `Element`
const searchValue = await page.$eval(
'#search',
(el: HTMLInputElement) => el.value
);
The compiler should be able to infer the return type
from the pageFunction
you provide. If it is unable to, you can use the generic
type to tell the compiler what return type you expect from $eval
:
// The compiler can infer the return type in this case, but if it can't
// or if you want to be more explicit, provide it as the generic type.
const searchValue = await page.$eval<string>(
'#search',
(el: HTMLInputElement) => el.value
);
Adds a <script>
tag into the page with the desired URL or content.
Options for the script.
An ElementHandle | element handle to the injected
<script>
element.
Adds a <link rel="stylesheet">
tag into the page with the desired URL or
a <style type="text/css">
tag with the content.
Shortcut for Frame.(addStyleTag:2) | page.mainFrame().addStyleTag(options).
An ElementHandle | element handle to the injected <link>
or <style>
element.
Abstract
authenticateAbstract
bringAbstract
browserAbstract
browserThis 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.
A selector
to search for element to click. If there are
multiple elements satisfying the selector
, the first will be clicked
Optional
options: Readonly<ClickOptions>Object
Promise which resolves when the element matching selector
is
successfully clicked. The Promise will be rejected if there is no element
matching selector
.
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),
]);
Shortcut for Frame.click | page.mainFrame().click(selector[, options]).
Abstract
closeAbstract
cookiesAbstract
createCDPSessionAbstract
createPDFStreamGenerates a PDF of the page with the print
CSS media type.
Optional
options: PDFOptionsoptions for generating the PDF.
To generate a PDF with the screen
media type, call
page.emulateMediaType('screen')
before
calling page.pdf()
.
By default, page.pdf()
generates a pdf with modified colors for printing.
Use the
-webkit-print-color-adjust
property to force rendering of exact colors.
Abstract
deleteEmit an event and call any associated listeners.
true
if there are any listeners, false
if there are not.
Emulates a given device's metrics and user agent.
To aid emulation, Puppeteer provides a list of known devices that can be via KnownDevices.
This method is a shortcut for calling two methods: Page.setUserAgent and Page.setViewport.
This method will resize the page. A lot of websites don't expect phones to change size, so you should emulate before navigating to the page.
import {KnownDevices} from 'puppeteer';
const iPhone = KnownDevices['iPhone 15 Pro'];
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.emulate(iPhone);
await page.goto('https://www.google.com');
// other actions...
await browser.close();
})();
Abstract
emulateCPUThrottlingAbstract
emulateEmulates the idle state. If no arguments set, clears idle state emulation.
Optional
overrides: { Mock idle state. If not set, clears idle overrides
Abstract
emulateOptional
features: MediaFeature[]<?Array<Object>>
Given an array of media feature
objects, emulates CSS media features on the page. Each media feature object
must have the following properties:
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.emulateMediaFeatures([
{name: 'prefers-reduced-motion', value: 'reduce'},
]);
await page.evaluate(
() => matchMedia('(prefers-reduced-motion: reduce)').matches
);
// → true
await page.evaluate(
() => matchMedia('(prefers-reduced-motion: 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-reduced-motion: reduce)').matches
);
// → true
await page.evaluate(
() => matchMedia('(prefers-reduced-motion: no-preference)').matches
);
// → false
await page.emulateMediaFeatures([{name: 'color-gamut', value: 'p3'}]);
await page.evaluate(() => matchMedia('(color-gamut: srgb)').matches);
// → true
await page.evaluate(() => matchMedia('(color-gamut: p3)').matches);
// → true
await page.evaluate(() => matchMedia('(color-gamut: rec2020)').matches);
// → false
Abstract
emulateOptional
type: stringChanges the CSS media type of the page. The only allowed
values are screen
, print
and null
. Passing null
disables CSS media
emulation.
await page.evaluate(() => matchMedia('screen').matches);
// → true
await page.evaluate(() => matchMedia('print').matches);
// → false
await page.emulateMediaType('print');
await page.evaluate(() => matchMedia('screen').matches);
// → false
await page.evaluate(() => matchMedia('print').matches);
// → true
await page.emulateMediaType(null);
await page.evaluate(() => matchMedia('screen').matches);
// → true
await page.evaluate(() => matchMedia('print').matches);
// → false
Abstract
emulateThis does not affect WebSockets and WebRTC PeerConnections (see https://crbug.com/563644). To set the page offline, you can use Page.setOfflineMode.
A list of predefined network conditions can be used by importing PredefinedNetworkConditions.
Passing null
disables network condition
emulation.
import {PredefinedNetworkConditions} from 'puppeteer';
const slow3G = PredefinedNetworkConditions['Slow 3G'];
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.emulateNetworkConditions(slow3G);
await page.goto('https://www.google.com');
// other actions...
await browser.close();
})();
Abstract
emulateOptional
timezoneId: stringChanges the timezone of the page. See
ICU’s metaZones.txt
for a list of supported timezone IDs. Passing
null
disables timezone emulation.
Abstract
emulateSimulates the given vision deficiency on the page.
Optional
type: the type of deficiency to simulate, or 'none'
to reset.
import puppeteer from 'puppeteer';
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://v8.dev/blog/10-years');
await page.emulateVisionDeficiency('achromatopsia');
await page.screenshot({path: 'achromatopsia.png'});
await page.emulateVisionDeficiency('deuteranopia');
await page.screenshot({path: 'deuteranopia.png'});
await page.emulateVisionDeficiency('blurredVision');
await page.screenshot({path: 'blurred-vision.png'});
await browser.close();
})();
Evaluates a function in the page's context and returns the result.
If the function passed to page.evaluate
returns a Promise, the
function will wait for the promise to resolve and return its value.
the return value of pageFunction
.
const result = await frame.evaluate(() => {
return Promise.resolve(8 * 7);
});
console.log(result); // prints "56"
You can pass a string instead of a function (although functions are recommended as they are easier to debug and use with TypeScript):
const aHandle = await page.evaluate('1 + 2');
To get the best TypeScript experience, you should pass in as the
generic the type of pageFunction
:
const aHandle = await page.evaluate(() => 2);
ElementHandle instances (including JSHandles) can be passed
as arguments to the pageFunction
:
const bodyHandle = await page.$('body');
const html = await page.evaluate(body => body.innerHTML, bodyHandle);
await bodyHandle.dispose();
The only difference between page.evaluate and
page.evaluateHandle
is that evaluateHandle
will return the value
wrapped in an in-page object.
If the function passed to page.evaluateHandle
returns a Promise, the
function will wait for the promise to resolve and return its value.
You can pass a string instead of a function (although functions are recommended as they are easier to debug and use with TypeScript):
const aHandle = await page.evaluateHandle('document');
JSHandle instances can be passed as arguments to the pageFunction
:
const aHandle = await page.evaluateHandle(() => document.body);
const resultHandle = await page.evaluateHandle(
body => body.innerHTML,
aHandle
);
console.log(await resultHandle.jsonValue());
await resultHandle.dispose();
Most of the time this function returns a JSHandle,
but if pageFunction
returns a reference to an element,
you instead get an ElementHandle back:
const button = await page.evaluateHandle(() =>
document.querySelector('button')
);
// can call `click` because `button` is an `ElementHandle`
await button.click();
The TypeScript definitions assume that evaluateHandle
returns
a JSHandle
, but if you know it's going to return an
ElementHandle
, pass it as the generic argument:
const button = await page.evaluateHandle<ElementHandle>(...);
Abstract
evaluateAdds a function which would be invoked in one of the following scenarios:
whenever the page is navigated
whenever the child frame is attached or navigated. In this case, the function is invoked in the context of the newly attached frame.
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:
// preload.js
// overwrite the `languages` property to use a custom getter
Object.defineProperty(navigator, 'languages', {
get: function () {
return ['en-US', 'en', 'bn'];
},
});
// In your puppeteer script, assuming the preload.js file is
// in same folder of our script.
const preloadFile = fs.readFileSync('./preload.js', 'utf8');
await page.evaluateOnNewDocument(preloadFile);
Abstract
exposeThe method adds a function called name
on the page's window
object.
When called, the function executes puppeteerFunction
in node.js and
returns a Promise
which resolves to the return value of
puppeteerFunction
.
If the puppeteerFunction returns a Promise
, it will be awaited.
:::note
Functions installed via page.exposeFunction
survive navigations.
:::
Name of the function on the window object
Callback function which will be called in Puppeteer's context.
An example of adding an md5
function into the page:
import puppeteer from 'puppeteer';
import crypto from 'crypto';
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
page.on('console', msg => console.log(msg.text()));
await page.exposeFunction('md5', text =>
crypto.createHash('md5').update(text).digest('hex')
);
await page.evaluate(async () => {
// use window.md5 to compute hashes
const myString = 'PUPPETEER';
const myHash = await window.md5(myString);
console.log(`md5 of ${myString} is ${myHash}`);
});
await browser.close();
})();
An example of adding a window.readfile
function into the page:
import puppeteer from 'puppeteer';
import fs from 'fs';
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
page.on('console', msg => console.log(msg.text()));
await page.exposeFunction('readfile', async filePath => {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf8', (err, text) => {
if (err) reject(err);
else resolve(text);
});
});
});
await page.evaluate(async () => {
// use window.readfile to read contents of a file
const content = await window.readfile('/etc/hosts');
console.log(content);
});
await browser.close();
})();
This method fetches an element with selector
and focuses it. If there's no
element matching selector
, the method throws an error.
A selector of an element to focus. If there are multiple elements satisfying the selector, the first will be focused.
Promise which resolves when the element matching selector is successfully focused. The promise will be rejected if there is no element matching selector.
Abstract
framesAbstract
getAbstract
goThis method navigate to the previous page in history.
Optional
options: WaitForOptionsNavigation parameters
Promise which resolves to the main resource response. In case of
multiple redirects, the navigation will resolve with the response of the
last redirect. If can not go back, resolves to null
.
Abstract
goThis method navigate to the next page in history.
Optional
options: WaitForOptionsNavigation Parameter
Promise which resolves to the main resource response. In case of
multiple redirects, the navigation will resolve with the response of the
last redirect. If can not go forward, resolves to null
.
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.
A selector to search for element to hover. If there are multiple elements satisfying the selector, the first will be hovered.
Promise which resolves when the element matching selector
is
successfully hovered. Promise gets rejected if there's no element matching
selector
.
Shortcut for page.mainFrame().hover(selector).
Abstract
isAbstract
istrue
if drag events are being intercepted, false
otherwise.
We no longer support intercepting drag payloads. Use the new drag APIs found on ElementHandle to drag (or just use the Page.mouse).
Abstract
isAbstract
isCreates a locator for the provided selector. See Locator for details and supported actions.
selector to query page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Creates a locator for the provided function. See Locator for details and supported actions.
Abstract
mainAbstract
metricsObject containing metrics as key/value pairs.
Timestamp
: The timestamp when the metrics sample was taken.
Documents
: Number of documents in the page.
Frames
: Number of frames in the page.
JSEventListeners
: Number of events in the page.
Nodes
: Number of DOM nodes in the page.
LayoutCount
: Total number of full or partial page layout.
RecalcStyleCount
: Total number of page style recalculations.
LayoutDuration
: Combined durations of all page layouts.
RecalcStyleDuration
: Combined duration of all page style
recalculations.
ScriptDuration
: Combined duration of JavaScript execution.
TaskDuration
: Combined duration of all tasks performed by the browser.
JSHeapUsedSize
: Used JavaScript heap size.
JSHeapTotalSize
: Total JavaScript heap size.
Remove an event listener from firing.
this
to enable you to chain method calls.
Bind an event listener to fire when an event occurs.
this
to enable you to chain method calls.
Like on
but the listener will only be fired once and then it will be removed.
this
to enable you to chain method calls.
Abstract
pdfGenerates a PDF of the page with the print
CSS media type.
Optional
options: PDFOptionsoptions for generating the PDF.
To generate a PDF with the screen
media type, call
page.emulateMediaType('screen')
before
calling page.pdf()
.
By default, page.pdf()
generates a pdf with modified colors for printing.
Use the
-webkit-print-color-adjust
property to force rendering of exact colors.
Abstract
queryThis method iterates the JavaScript heap and finds all objects with the given prototype.
a handle to the object prototype.
Promise which resolves to a handle to an array of objects with this prototype.
// Create a Map object
await page.evaluate(() => (window.map = new Map()));
// Get a handle to the Map object prototype
const mapPrototype = await page.evaluateHandle(() => Map.prototype);
// Query all map instances into an array
const mapInstances = await page.queryObjects(mapPrototype);
// Count amount of map objects in heap
const count = await page.evaluate(maps => maps.length, mapInstances);
await mapInstances.dispose();
await mapPrototype.dispose();
Abstract
reloadReloads the page.
Optional
options: WaitForOptionsOptions to configure waiting behavior.
A promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
Abstract
removeThe method removes a previously added function via $Page.exposeFunction
called name
from the page's window
object.
Abstract
removeExperimental
Captures a screencast of this page.
Optional
options: Readonly<ScreencastOptions>Configures screencast behavior.
Recording a page:
import puppeteer from 'puppeteer';
// Launch a browser
const browser = await puppeteer.launch();
// Create a new page
const page = await browser.newPage();
// Go to your site.
await page.goto("https://www.example.com");
// Start recording.
const recorder = await page.screencast({path: 'recording.webm'});
// Do something.
// Stop recording.
await recorder.stop();
browser.close();
All recordings will be WebM format using the VP9 video codec. The FPS is 30.
You must have ffmpeg installed on your system.
Captures a screenshot of this page.
Configures screenshot behavior.
While a screenshot is being taken in a BrowserContext, the following methods will automatically wait for the screenshot to finish to prevent interference with the screenshot process: BrowserContext.newPage, Browser.newPage, Page.close.
Calling Page.bringToFront will not wait for existing screenshot operations.
Optional
options: Readonly<ScreenshotOptions>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.
A Selector to query the page for
Rest
...values: 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.
Abstract
setAbstract
setAbstract
setAbstract
setAbstract
setAbstract
setAbstract
setWhether to enable drag interception.
We no longer support intercepting drag payloads. Use the new drag APIs found on ElementHandle to drag (or just use the Page.mouse).
Abstract
setThe extra HTTP headers will be sent with every request the page initiates.
:::tip
All HTTP header names are lowercased. (HTTP headers are case-insensitive, so this shouldn’t impact your server code.)
:::
:::note
page.setExtraHTTPHeaders does not guarantee the order of headers in the outgoing requests.
:::
An object containing additional HTTP headers to be sent with every request. All header values must be strings.
Abstract
setAbstract
setAbstract
setSets the network connection to offline.
It does not change the parameters used in Page.emulateNetworkConditions
When true
, enables offline mode for the page.
Abstract
setActivating request interception enables HTTPRequest.abort, HTTPRequest.continue and HTTPRequest.respond methods. This provides the capability to modify network requests that are made by a page.
Once request interception is enabled, every request will stall unless it's continued, responded or aborted; or completed using the browser cache.
See the interception guide for more details.
Whether to enable request interception.
An example of a naïve request interceptor that aborts all image requests:
import puppeteer from 'puppeteer';
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on('request', interceptedRequest => {
if (
interceptedRequest.url().endsWith('.png') ||
interceptedRequest.url().endsWith('.jpg')
)
interceptedRequest.abort();
else interceptedRequest.continue();
});
await page.goto('https://example.com');
await browser.close();
})();
Abstract
setAbstract
setpage.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.
In the case of multiple pages in a single browser, each page can have its
own viewport size. Setting the viewport to null
resets the viewport to
its default value.
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.
A Selector to search for element to tap. If there are multiple elements satisfying the selector, the first will be tapped.
Abstract
targetA target this page was created from.
Use Page.createCDPSession directly.
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.
A selector of an element to type into. If there are multiple elements satisfying the selector, the first will be used.
A text to type into a focused element.
Optional
options: Readonly<KeyboardTypeOptions>have property delay
which is the Time to wait between
key presses in milliseconds. Defaults to 0
.
Abstract
viewportReturns the current page viewport settings without checking the actual page viewport.
This is either the viewport set with the previous Page.setViewport call or the default viewport set via BrowserConnectOptions.defaultViewport | BrowserConnectOptions.defaultViewport.
Abstract
waitThis method is typically coupled with an action that triggers a device request from an api such as WebBluetooth.
:::caution
This must be called before the device request is made. It will not return a currently active device prompt.
:::
Optional
options: WaitTimeoutOptionsAbstract
waitThis method is typically coupled with an action that triggers file choosing.
:::caution
This must be called before the file chooser is launched. It will not return a currently active file chooser.
:::
:::caution
Interception of file dialogs triggered via DOM APIs such as window.showOpenFilePicker is currently not supported.
:::
Optional
options: WaitTimeoutOptionsIn the "headful" browser, this method results in the native file picker
dialog not showing up
for the user.
The following example clicks a button that issues a file chooser
and then responds with /tmp/myfile.pdf
as if a user has selected this file.
const [fileChooser] = await Promise.all([
page.waitForFileChooser(),
page.click('#upload-file-button'),
// some button that triggers file selection
]);
await fileChooser.accept(['/tmp/myfile.pdf']);
Waits for the provided function, pageFunction
, to return a truthy value when
evaluated in the page's context.
Page.waitForFunction can be used to observe a viewport size change:
import puppeteer from 'puppeteer';
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const watchDog = page.waitForFunction('window.innerWidth < 100');
await page.setViewport({width: 50, height: 50});
await watchDog;
await browser.close();
})();
Arguments can be passed from Node.js to pageFunction
:
const selector = '.foo';
await page.waitForFunction(
selector => !!document.querySelector(selector),
{},
selector
);
The provided pageFunction
can be asynchronous:
const username = 'github-username';
await page.waitForFunction(
async username => {
const githubResponse = await fetch(
`https://api.github.com/users/${username}`
);
const githubUser = await githubResponse.json();
// show the avatar
const img = document.createElement('img');
img.src = githubUser.avatar_url;
// wait 3 seconds
await new Promise((resolve, reject) => setTimeout(resolve, 3000));
img.remove();
},
{},
username
);
Waits for the page to navigate to a new URL or to reload. It is useful when you run code that will indirectly cause the page to navigate.
Optional
options: WaitForOptionsNavigation parameters which might have the following properties:
A Promise
which resolves to the main resource response.
null
.const [response] = await Promise.all([
page.waitForNavigation(), // The promise resolves after navigation has finished
page.click('a.my-link'), // Clicking the link will indirectly cause a navigation
]);
Usage of the History API to change the URL is considered a navigation.
A URL or predicate to wait for
Optional
options: WaitTimeoutOptionsOptional waiting parameters
Promise which resolves to the matched request
const firstRequest = await page.waitForRequest(
'https://example.com/resource'
);
const finalRequest = await page.waitForRequest(
request => request.url() === 'https://example.com'
);
return finalRequest.response()?.ok();
Optional Waiting Parameters have:
timeout
: Maximum wait time in milliseconds, defaults to 30
seconds, pass
0
to disable the timeout. The default value can be changed by using the
Page.setDefaultTimeout method.A URL or predicate to wait for.
Optional
options: WaitTimeoutOptionsOptional waiting parameters
Promise which resolves to the matched response.
const firstResponse = await page.waitForResponse(
'https://example.com/resource'
);
const finalResponse = await page.waitForResponse(
response =>
response.url() === 'https://example.com' && response.status() === 200
);
const finalResponse = await page.waitForResponse(async response => {
return (await response.text()).includes('<html>');
});
return finalResponse.ok();
Optional Parameter have:
timeout
: Maximum wait time in milliseconds, defaults to 30
seconds,
pass 0
to disable the timeout. The default value can be changed by using
the Page.setDefaultTimeout 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.
Promise which resolves when element specified by selector string
is added to DOM. Resolves to null
if waiting for hidden: true
and
selector is not found in DOM.
This method works across navigations:
import puppeteer from 'puppeteer';
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
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 browser.close();
})();
The optional Parameter in Arguments options
are:
visible
: A 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
: 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
: 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 method.
Abstract
workersAll of the dedicated WebWorkers associated with the page.
Page provides methods to interact with a single tab or extension background page in the browser.
:::note
One Browser instance might have multiple Page instances.
:::
Example
This example creates a page, navigates it to a URL, and then saves a screenshot:
The Page class extends from Puppeteer's EventEmitter class and will emit various events which are documented in the PageEvent enum.
Example
This example logs a message for a single page
load
event:To unsubscribe from events use the EventEmitter.off method: