Skip to main content
Go to Latest
class Page
extends EventEmitter
Re-export
import { Page } from "https://deno.land/x/puppeteer@14.1.1/vendor/puppeteer-core/puppeteer/api-docs-entry.d.ts";

Page provides methods to interact with a single tab or extension background page in Chromium.

Examples

This example creates a page, navigates it to a URL, and then * saves a screenshot:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com');
  await page.screenshot({path: 'screenshot.png'});
  await browser.close();
})();

The Page class extends from Puppeteer's EventEmitter class and will emit various events which are documented in the PageEmittedEvents enum.

This example logs a message for a single page load event:

page.once('load', () => console.log('Page loaded!'));

To unsubscribe from events use the off method:

function logRequest(interceptedRequest) {
  console.log('A request was made:', interceptedRequest.url());
}
page.on('request', logRequest);
// Sometime later...
page.off('request', logRequest);

Constructors

new
Page(
client: CDPSession,
target: Target,
ignoreHTTPSErrors: boolean,
screenshotTaskQueue: TaskQueue,
)

Properties

private
_accessibility
private
_addConsoleMessage
private
_buildMetricsObject
private
_client
private
_closed
private
_coverage
private
optional
_disconnectPromise
private
_emitMetrics
private
_emulationManager
private
_fileChooserInterceptors
private
_frameManager
private
_go
private
_handleException
private
_handlerMap
private
_initialize
private
_javascriptEnabled
private
_keyboard
private
_mouse
private
_onBindingCalled
private
_onConsoleAPI
private
_onDialog
private
_onFileChooser
private
_onLogEntryAdded
private
_onTargetCrashed
private
_pageBindings
private
_resetDefaultBackgroundColor

Resets default white background

private
_screenshotTask
private
_screenshotTaskQueue
private
_sessionClosePromise
private
_setTransparentBackgroundColor

Hides default white background

private
_target
private
_timeoutSettings
private
_touchscreen
private
_tracing
private
_userDragInterceptionEnabled
private
_viewport
private
_workers
readonly
accessibility: Accessibility
readonly
coverage: Coverage
readonly
keyboard: Keyboard
readonly
mouse: Mouse
readonly
touchscreen: Touchscreen
readonly
tracing: Tracing

Methods

$<T extends any = any>(selector: string): Promise<ElementHandle<T> | null>

Runs document.querySelector within the page. If no element matches the selector, the return value resolves to null.

$$<T extends any = any>(selector: string): Promise<Array<ElementHandle<T>>>

The method runs document.querySelectorAll within the page. If no elements match the selector, the return value resolves to [].

$$eval<ReturnType>(
selector: string,
pageFunction: (elements: any[], ...args: unknown[]) => ReturnType | Promise<ReturnType>,
): Promise<WrapElementHandle<ReturnType>>

This method runs Array.from(document.querySelectorAll(selector)) within the page and passes the result as the first argument to the pageFunction.

$eval<ReturnType>(
selector: string,
pageFunction: (element: any, ...args: unknown[]) => ReturnType | Promise<ReturnType>,
): Promise<WrapElementHandle<ReturnType>>

This method runs document.querySelector within the page and passes the result as the first argument to the pageFunction.

$x(expression: string): Promise<ElementHandle[]>

The method evaluates the XPath expression relative to the page document as its context node. If there are no such elements, the method resolves to an empty array.

addScriptTag(options: { url?: string; path?: string; content?: string; type?: string; id?: string; }): Promise<ElementHandle>

Adds a <script> tag into the page with the desired URL or content.

addStyleTag(options: { url?: string; path?: string; content?: string; }): Promise<ElementHandle>

Adds a <link rel="stylesheet"> tag into the page with the desired URL or a <style type="text/css"> tag with the content.

authenticate(credentials: Credentials): Promise<void>

Provide credentials for HTTP authentication.

bringToFront(): Promise<void>

Brings page to front (activates tab).

Get the browser the page belongs to.

Get the browser context that the page belongs to.

click(selector: string, options?: { delay?: number; button?: MouseButton; clickCount?: number; }): Promise<void>

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.

Get the CDP session client the page belongs to.

close(options?: { runBeforeUnload?: boolean; }): Promise<void>
content(): Promise<string>
cookies(...urls: string[]): Promise<Protocol.Network.Cookie[]>

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.

Generates a PDF of the page with the print CSS media type.

emulate(options: { viewport: Viewport; userAgent: string; }): Promise<void>

Emulates given device metrics and user agent. This method is a shortcut for calling two methods: Page.setUserAgent and Page.setViewport To aid emulation, Puppeteer provides a list of device descriptors that can be obtained via the Puppeteer.devices 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.

emulateCPUThrottling(factor: number | null): Promise<void>

Enables CPU throttling to emulate slow CPUs.

emulateIdleState(overrides?: { isUserActive: boolean; isScreenUnlocked: boolean; }): Promise<void>

Emulates the idle state. If no arguments set, clears idle state emulation.

emulateMediaFeatures(features?: MediaFeature[]): Promise<void>
emulateMediaType(type?: string): Promise<void>
emulateNetworkConditions(networkConditions: NetworkConditions | null): Promise<void>
emulateTimezone(timezoneId?: string): Promise<void>

Simulates the given vision deficiency on the page.

evaluate<T extends EvaluateFn>(pageFunction: T, ...args: SerializableOrJSHandle[]): Promise<UnwrapPromiseLike<EvaluateFnReturnType<T>>>
evaluateHandle<HandlerType extends JSHandle = JSHandle>(pageFunction: EvaluateHandleFn, ...args: SerializableOrJSHandle[]): Promise<HandlerType>
evaluateOnNewDocument(pageFunction: Function | string, ...args: unknown[]): Promise<void>

Adds 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.

exposeFunction(name: string, puppeteerFunction: Function | { default: Function; }): Promise<void>

The 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.

focus(selector: string): Promise<void>

This method fetches an element with selector and focuses it. If there's no element matching selector, the method throws an error.

goBack(options?: WaitForOptions): Promise<HTTPResponse | null>

This method navigate to the previous page in history.

goForward(options?: WaitForOptions): Promise<HTTPResponse | null>

This method navigate to the next page in history.

goto(url: string, options?: WaitForOptions & { referer?: string; }): Promise<HTTPResponse>
hover(selector: string): Promise<void>

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.

isClosed(): boolean

Indicates that the page has been closed.

metrics(): Promise<Metrics>
off<K extends keyof PageEventObject>(eventName: K, handler: (event: PageEventObject[K]) => void): EventEmitter
on<K extends keyof PageEventObject>(eventName: K, handler: (event: PageEventObject[K]) => void): EventEmitter

Listen to page events.

once<K extends keyof PageEventObject>(eventName: K, handler: (event: PageEventObject[K]) => void): EventEmitter
pdf(options?: PDFOptions): Promise<Uint8Array>
queryObjects(prototypeHandle: JSHandle): Promise<JSHandle>

This method iterates the JavaScript heap and finds all objects with the given prototype.

reload(options?: WaitForOptions): Promise<HTTPResponse | null>
screenshot(options?: ScreenshotOptions): Promise<Uint8Array | string>
select(selector: string, ...values: string[]): Promise<string[]>

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.

setBypassCSP(enabled: boolean): Promise<void>

Toggles bypassing page's Content-Security-Policy.

setCacheEnabled(enabled?: boolean): Promise<void>

Toggles ignoring cache for each request based on the enabled state. By default, caching is enabled.

setContent(html: string, options?: WaitForOptions): Promise<void>
setCookie(...cookies: Protocol.Network.CookieParam[]): Promise<void>
setDefaultNavigationTimeout(timeout: number): void

This setting will change the default maximum navigation time for the following methods and related shortcuts:

  • Page.goBack | page.goBack(options)

  • Page.goForward | page.goForward(options)

  • Page.goto | page.goto(url,options)

  • Page.reload | page.reload(options)

  • Page.setContent | page.setContent(html,options)

  • Page.waitForNavigation | page.waitForNavigation(options)

setDefaultTimeout(timeout: number): void
setDragInterception(enabled: boolean): Promise<void>
setExtraHTTPHeaders(headers: Record<string, string>): Promise<void>

The extra HTTP headers will be sent with every request the page initiates. NOTE: 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.

setGeolocation(options: GeolocationOptions): Promise<void>

Sets the page's geolocation.

setJavaScriptEnabled(enabled: boolean): Promise<void>
setOfflineMode(enabled: boolean): Promise<void>
setRequestInterception(value: boolean): Promise<void>
setUserAgent(userAgent: string, userAgentMetadata?: Protocol.Emulation.UserAgentMetadata): Promise<void>
setViewport(viewport: Viewport): Promise<void>

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.

In the case of multiple pages in a single browser, each page can have its own viewport size.

tap(selector: string): Promise<void>

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.

title(): Promise<string>
type(
selector: string,
text: string,
options?: { delay: number; },
): Promise<void>

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.

url(): string
viewport(): Viewport | null
deprecated
waitFor(
selectorOrFunctionOrTimeout: string | number | Function,
options?: { visible?: boolean; hidden?: boolean; timeout?: number; polling?: string | number; },
): Promise<JSHandle>

This method is typically coupled with an action that triggers file choosing. 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']);

NOTE: This must be called before the file chooser is launched. It will not return a currently active file chooser.

waitForFrame(urlOrPredicate: string | ((frame: Frame) => boolean | Promise<boolean>), options?: { timeout?: number; }): Promise<Frame>
waitForFunction(
pageFunction: Function | string,
options?: { timeout?: number; polling?: string | number; },
): Promise<JSHandle>

The waitForFunction can be used to observe viewport size change:

const puppeteer = require('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();
})();

To pass arguments from node.js to the predicate of page.waitForFunction function:

const selector = '.foo';
await page.waitForFunction(
(selector) => !!document.querySelector(selector),
{},
selector
);

The predicate of page.waitForFunction can be asynchronous too:

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
);
waitForNavigation(options?: WaitForOptions): Promise<HTTPResponse | null>

This resolves when the page navigates to a new URL or reloads. It is useful when you run code that will indirectly cause the page to navigate. Consider this example:

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
]);
waitForNetworkIdle(options?: { idleTime?: number; timeout?: number; }): Promise<void>
waitForRequest(urlOrPredicate: string | ((req: HTTPRequest) => boolean | Promise<boolean>), options?: { timeout?: number; }): Promise<HTTPRequest>
waitForResponse(urlOrPredicate: string | ((res: HTTPResponse) => boolean | Promise<boolean>), options?: { timeout?: number; }): Promise<HTTPResponse>
waitForSelector(selector: string, options?: { visible?: boolean; hidden?: boolean; timeout?: number; }): Promise<ElementHandle | null>

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:

const puppeteer = require('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();
})();
waitForTimeout(milliseconds: number): Promise<void>

Causes your script to wait for the given number of milliseconds.

waitForXPath(xpath: string, options?: { visible?: boolean; hidden?: boolean; timeout?: number; }): Promise<ElementHandle | null>

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 navigation

const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
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 browser.close();
})();

Static Methods

create(
client: CDPSession,
target: Target,
ignoreHTTPSErrors: boolean,
defaultViewport: Viewport | null,
screenshotTaskQueue: TaskQueue,
): Promise<Page>