puppeteer/docs/api/puppeteer.page.md

167 lines
66 KiB
Markdown
Raw Normal View History

2022-07-05 13:41:43 +00:00
---
sidebar_label: Page
---
# Page class
Page provides methods to interact with a single tab or [extension background page](https://developer.chrome.com/extensions/background_pages) in the browser.
2022-07-05 13:41:43 +00:00
:::note
One Browser instance might have multiple Page instances.
:::
#### Signature:
2022-07-05 13:41:43 +00:00
```typescript
export declare abstract class Page extends EventEmitter<PageEvents>
2022-07-05 13:41:43 +00:00
```
2023-09-13 13:47:55 +00:00
**Extends:** [EventEmitter](./puppeteer.eventemitter.md)&lt;[PageEvents](./puppeteer.pageevents.md)&gt;
2022-07-05 13:41:43 +00:00
## Remarks
The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the `Page` class.
## Example 1
This example creates a page, navigates it to a URL, and then saves a screenshot:
```ts
import puppeteer from 'puppeteer';
2022-07-05 13:41:43 +00:00
(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();
})();
```
2023-09-13 13:47:55 +00:00
The Page class extends from Puppeteer's [EventEmitter](./puppeteer.eventemitter.md) class and will emit various events which are documented in the [PageEvent](./puppeteer.pageevent.md) enum.
2022-07-05 13:41:43 +00:00
## Example 2
This example logs a message for a single page `load` event:
```ts
page.once('load', () => console.log('Page loaded!'));
```
2023-09-13 13:47:55 +00:00
To unsubscribe from events use the [EventEmitter.off()](./puppeteer.eventemitter.off.md) method:
2022-07-05 13:41:43 +00:00
```ts
function logRequest(interceptedRequest) {
console.log('A request was made:', interceptedRequest.url());
}
page.on('request', logRequest);
// Sometime later...
page.off('request', logRequest);
```
## Properties
| Property | Modifiers | Type | Description |
| ------------- | --------------------- | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| accessibility | <code>readonly</code> | [Accessibility](./puppeteer.accessibility.md) | The Accessibility class provides methods for inspecting the browser's accessibility tree. The accessibility tree is used by assistive technology such as [screen readers](https://en.wikipedia.org/wiki/Screen_reader) or [switches](https://en.wikipedia.org/wiki/Switch_access). |
| coverage | <code>readonly</code> | [Coverage](./puppeteer.coverage.md) | The Coverage class provides methods to gather information about parts of JavaScript and CSS that were used by the page. |
| keyboard | <code>readonly</code> | [Keyboard](./puppeteer.keyboard.md) | Keyboard provides an api for managing a virtual keyboard. The high level api is [Keyboard.type()](./puppeteer.keyboard.type.md), which takes raw characters and generates proper keydown, keypress/input, and keyup events on your page. |
| mouse | <code>readonly</code> | [Mouse](./puppeteer.mouse.md) | The Mouse class operates in main-frame CSS pixels relative to the top-left corner of the viewport. |
| touchscreen | <code>readonly</code> | [Touchscreen](./puppeteer.touchscreen.md) | The Touchscreen class exposes touchscreen events. |
| tracing | <code>readonly</code> | [Tracing](./puppeteer.tracing.md) | The Tracing class exposes the tracing audit interface. |
2022-07-05 13:41:43 +00:00
## Methods
| Method | Modifiers | Description |
| ---------------------------------------------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [$](./puppeteer.page._.md) | | Runs <code>document.querySelector</code> within the page. If no element matches the selector, the return value resolves to <code>null</code>. |
| [$$](./puppeteer.page.__.md) | | The method runs <code>document.querySelectorAll</code> within the page. If no elements match the selector, the return value resolves to <code>[]</code>. |
| [$$eval](./puppeteer.page.__eval.md) | | This method runs <code>Array.from(document.querySelectorAll(selector))</code> within the page and passes the result as the first argument to the <code>pageFunction</code>. |
| [$eval](./puppeteer.page._eval.md) | | This method runs <code>document.querySelector</code> within the page and passes the result as the first argument to the <code>pageFunction</code>. |
| [$x](./puppeteer.page._x.md) | | 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](./puppeteer.page.addscripttag.md) | | Adds a <code>&lt;script&gt;</code> tag into the page with the desired URL or content. |
| [addStyleTag](./puppeteer.page.addstyletag.md) | | <p>Adds a <code>&lt;link rel=&quot;stylesheet&quot;&gt;</code> tag into the page with the desired URL or a <code>&lt;style type=&quot;text/css&quot;&gt;</code> tag with the content.</p><p>Shortcut for [page.mainFrame().addStyleTag(options)](./puppeteer.frame.addstyletag_1.md).</p> |
| [addStyleTag](./puppeteer.page.addstyletag_1.md) | | |
| [authenticate](./puppeteer.page.authenticate.md) | | Provide credentials for <code>HTTP authentication</code>. |
| [bringToFront](./puppeteer.page.bringtofront.md) | | Brings page to front (activates tab). |
| [browser](./puppeteer.page.browser.md) | | Get the browser the page belongs to. |
| [browserContext](./puppeteer.page.browsercontext.md) | | Get the browser context that the page belongs to. |
| [click](./puppeteer.page.click.md) | | This method fetches an element with <code>selector</code>, scrolls it into view if needed, and then uses [Page.mouse](./puppeteer.page.md) to click in the center of the element. If there's no element matching <code>selector</code>, the method throws an error. |
| [close](./puppeteer.page.close.md) | | |
| [content](./puppeteer.page.content.md) | | The full HTML contents of the page, including the DOCTYPE. |
| [cookies](./puppeteer.page.cookies.md) | | 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. |
| [createCDPSession](./puppeteer.page.createcdpsession.md) | | Creates a Chrome Devtools Protocol session attached to the page. |
| [createPDFStream](./puppeteer.page.createpdfstream.md) | | Generates a PDF of the page with the <code>print</code> CSS media type. |
| [deleteCookie](./puppeteer.page.deletecookie.md) | | |
| [emulate](./puppeteer.page.emulate.md) | | <p>Emulates a given device's metrics and user agent.</p><p>To aid emulation, Puppeteer provides a list of known devices that can be via [KnownDevices](./puppeteer.knowndevices.md).</p> |
| [emulateCPUThrottling](./puppeteer.page.emulatecputhrottling.md) | | Enables CPU throttling to emulate slow CPUs. |
| [emulateIdleState](./puppeteer.page.emulateidlestate.md) | | Emulates the idle state. If no arguments set, clears idle state emulation. |
| [emulateMediaFeatures](./puppeteer.page.emulatemediafeatures.md) | | |
| [emulateMediaType](./puppeteer.page.emulatemediatype.md) | | |
| [emulateNetworkConditions](./puppeteer.page.emulatenetworkconditions.md) | | <p>This does not affect WebSockets and WebRTC PeerConnections (see https://crbug.com/563644). To set the page offline, you can use [Page.setOfflineMode()](./puppeteer.page.setofflinemode.md).</p><p>A list of predefined network conditions can be used by importing [PredefinedNetworkConditions](./puppeteer.predefinednetworkconditions.md).</p> |
| [emulateTimezone](./puppeteer.page.emulatetimezone.md) | | |
| [emulateVisionDeficiency](./puppeteer.page.emulatevisiondeficiency.md) | | Simulates the given vision deficiency on the page. |
| [evaluate](./puppeteer.page.evaluate.md) | | <p>Evaluates a function in the page's context and returns the result.</p><p>If the function passed to <code>page.evaluate</code> returns a Promise, the function will wait for the promise to resolve and return its value.</p> |
| [evaluateHandle](./puppeteer.page.evaluatehandle.md) | | |
| [evaluateOnNewDocument](./puppeteer.page.evaluateonnewdocument.md) | | <p>Adds a function which would be invoked in one of the following scenarios:</p><p>- whenever the page is navigated</p><p>- whenever the child frame is attached or navigated. In this case, the function is invoked in the context of the newly attached frame.</p><p>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 <code>Math.random</code>.</p> |
| [exposeFunction](./puppeteer.page.exposefunction.md) | | <p>The method adds a function called <code>name</code> on the page's <code>window</code> object. When called, the function executes <code>puppeteerFunction</code> in node.js and returns a <code>Promise</code> which resolves to the return value of <code>puppeteerFunction</code>.</p><p>If the puppeteerFunction returns a <code>Promise</code>, it will be awaited.</p><p>:::note</p><p>Functions installed via <code>page.exposeFunction</code> survive navigations.</p><p>:::note</p> |
| [focus](./puppeteer.page.focus.md) | | This method fetches an element with <code>selector</code> and focuses it. If there's no element matching <code>selector</code>, the method throws an error. |
| [frames](./puppeteer.page.frames.md) | | An array of all frames attached to the page. |
| [getDefaultTimeout](./puppeteer.page.getdefaulttimeout.md) | | Maximum time in milliseconds. |
| [goBack](./puppeteer.page.goback.md) | | This method navigate to the previous page in history. |
| [goForward](./puppeteer.page.goforward.md) | | This method navigate to the next page in history. |
| [goto](./puppeteer.page.goto.md) | | Navigates the page to the given <code>url</code>. |
| [hover](./puppeteer.page.hover.md) | | This method fetches an element with <code>selector</code>, scrolls it into view if needed, and then uses [Page.mouse](./puppeteer.page.md) to hover over the center of the element. If there's no element matching <code>selector</code>, the method throws an error. |
| [isClosed](./puppeteer.page.isclosed.md) | | Indicates that the page has been closed. |
| [isDragInterceptionEnabled](./puppeteer.page.isdraginterceptionenabled.md) | | <code>true</code> if drag events are being intercepted, <code>false</code> otherwise. |
| [isJavaScriptEnabled](./puppeteer.page.isjavascriptenabled.md) | | <code>true</code> if the page has JavaScript enabled, <code>false</code> otherwise. |
| [isServiceWorkerBypassed](./puppeteer.page.isserviceworkerbypassed.md) | | <code>true</code> if the service worker are being bypassed, <code>false</code> otherwise. |
| [locator](./puppeteer.page.locator.md) | | Creates a locator for the provided selector. See [Locator](./puppeteer.locator.md) for details and supported actions. |
| [locator](./puppeteer.page.locator_1.md) | | Creates a locator for the provided function. See [Locator](./puppeteer.locator.md) for details and supported actions. |
| [mainFrame](./puppeteer.page.mainframe.md) | | The page's main frame. |
| [metrics](./puppeteer.page.metrics.md) | | Object containing metrics as key/value pairs. |
| [pdf](./puppeteer.page.pdf.md) | | Generates a PDF of the page with the <code>print</code> CSS media type. |
| [queryObjects](./puppeteer.page.queryobjects.md) | | This method iterates the JavaScript heap and finds all objects with the given prototype. |
| [reload](./puppeteer.page.reload.md) | | Reloads the page. |
| [removeExposedFunction](./puppeteer.page.removeexposedfunction.md) | | The method removes a previously added function via $[Page.exposeFunction()](./puppeteer.page.exposefunction.md) called <code>name</code> from the page's <code>window</code> object. |
| [removeScriptToEvaluateOnNewDocument](./puppeteer.page.removescripttoevaluateonnewdocument.md) | | Removes script that injected into page by Page.evaluateOnNewDocument. |
| [screencast](./puppeteer.page.screencast.md) | | Captures a screencast of this [page](./puppeteer.page.md). |
| [screenshot](./puppeteer.page.screenshot.md) | | Captures a screenshot of this [page](./puppeteer.page.md). |
| [screenshot](./puppeteer.page.screenshot_1.md) | | |
| [select](./puppeteer.page.select.md) | | Triggers a <code>change</code> and <code>input</code> event once all the provided options have been selected. If there's no <code>&lt;select&gt;</code> element matching <code>selector</code>, the method throws an error. |
| [setBypassCSP](./puppeteer.page.setbypasscsp.md) | | Toggles bypassing page's Content-Security-Policy. |
| [setBypassServiceWorker](./puppeteer.page.setbypassserviceworker.md) | | Toggles ignoring of service worker for each request. |
| [setCacheEnabled](./puppeteer.page.setcacheenabled.md) | | Toggles ignoring cache for each request based on the enabled state. By default, caching is enabled. |
| [setContent](./puppeteer.page.setcontent.md) | | Set the content of the page. |
| [setCookie](./puppeteer.page.setcookie.md) | | |
| [setDefaultNavigationTimeout](./puppeteer.page.setdefaultnavigationtimeout.md) | | <p>This setting will change the default maximum navigation time for the following methods and related shortcuts:</p><p>- [page.goBack(options)](./puppeteer.page.goback.md)</p><p>- [page.goForward(options)](./puppeteer.page.goforward.md)</p><p>- [page.goto(url,options)](./puppeteer.page.goto.md)</p><p>- [page.reload(options)](./puppeteer.page.reload.md)</p><p>- [page.setContent(html,options)](./puppeteer.page.setcontent.md)</p><p>- [page.waitForNavigation(options)](./puppeteer.page.waitfornavigation.md)</p> |
| [setDefaultTimeout](./puppeteer.page.setdefaulttimeout.md) | | |
| [setDragInterception](./puppeteer.page.setdraginterception.md) | | |
| [setExtraHTTPHeaders](./puppeteer.page.setextrahttpheaders.md) | | <p>The extra HTTP headers will be sent with every request the page initiates.</p><p>:::tip</p><p>All HTTP header names are lowercased. (HTTP headers are case-insensitive, so this shouldnt impact your server code.)</p><p>:::</p><p>:::note</p><p>page.setExtraHTTPHeaders does not guarantee the order of headers in the outgoing requests.</p><p>:::</p> |
| [setGeolocation](./puppeteer.page.setgeolocation.md) | | Sets the page's geolocation. |
| [setJavaScriptEnabled](./puppeteer.page.setjavascriptenabled.md) | | |
| [setOfflineMode](./puppeteer.page.setofflinemode.md) | | <p>Sets the network connection to offline.</p><p>It does not change the parameters used in [Page.emulateNetworkConditions()](./puppeteer.page.emulatenetworkconditions.md)</p> |
| [setRequestInterception](./puppeteer.page.setrequestinterception.md) | | <p>Activating request interception enables [HTTPRequest.abort()](./puppeteer.httprequest.abort.md), [HTTPRequest.continue()](./puppeteer.httprequest.continue.md) and [HTTPRequest.respond()](./puppeteer.httprequest.respond.md) methods. This provides the capability to modify network requests that are made by a page.</p><p>Once request interception is enabled, every request will stall unless it's continued, responded or aborted; or completed using the browser cache.</p><p>See the [Request interception guide](https://pptr.dev/next/guides/request-interception) for more details.</p> |
| [setUserAgent](./puppeteer.page.setuseragent.md) | | |
| [setViewport](./puppeteer.page.setviewport.md) | | <p><code>page.setViewport</code> 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.</p><p>In the case of multiple pages in a single browser, each page can have its own viewport size.</p> |
| [tap](./puppeteer.page.tap.md) | | This method fetches an element with <code>selector</code>, scrolls it into view if needed, and then uses [Page.touchscreen](./puppeteer.page.md) to tap in the center of the element. If there's no element matching <code>selector</code>, the method throws an error. |
| [target](./puppeteer.page.target.md) | | A target this page was created from. |
| [title](./puppeteer.page.title.md) | | The page's title |
| [type](./puppeteer.page.type.md) | | <p>Sends a <code>keydown</code>, <code>keypress/input</code>, and <code>keyup</code> event for each character in the text.</p><p>To press a special key, like <code>Control</code> or <code>ArrowDown</code>, use [Keyboard.press()](./puppeteer.keyboard.press.md).</p> |
| [url](./puppeteer.page.url.md) | | The page's URL. |
| [viewport](./puppeteer.page.viewport.md) | | <p>Returns the current page viewport settings without checking the actual page viewport.</p><p>This is either the viewport set with the previous [Page.setViewport()](./puppeteer.page.setviewport.md) call or the default viewport set via [BrowserConnectOptions.defaultViewport](./puppeteer.browserconnectoptions.md).</p> |
| [waitForDevicePrompt](./puppeteer.page.waitfordeviceprompt.md) | | <p>This method is typically coupled with an action that triggers a device request from an api such as WebBluetooth.</p><p>:::caution</p><p>This must be called before the device request is made. It will not return a currently active device prompt.</p><p>:::</p> |
| [waitForFileChooser](./puppeteer.page.waitforfilechooser.md) | | <p>This method is typically coupled with an action that triggers file choosing.</p><p>:::caution</p><p>This must be called before the file chooser is launched. It will not return a currently active file chooser.</p><p>:::</p> |
| [waitForFrame](./puppeteer.page.waitforframe.md) | | Waits for a frame matching the given conditions to appear. |
| [waitForFunction](./puppeteer.page.waitforfunction.md) | | Waits for the provided function, <code>pageFunction</code>, to return a truthy value when evaluated in the page's context. |
| [waitForNavigation](./puppeteer.page.waitfornavigation.md) | | 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. |
| [waitForNetworkIdle](./puppeteer.page.waitfornetworkidle.md) | | |
| [waitForRequest](./puppeteer.page.waitforrequest.md) | | |
| [waitForResponse](./puppeteer.page.waitforresponse.md) | | |
| [waitForSelector](./puppeteer.page.waitforselector.md) | | Wait for the <code>selector</code> to appear in page. If at the moment of calling the method the <code>selector</code> already exists, the method will return immediately. If the <code>selector</code> doesn't appear after the <code>timeout</code> milliseconds of waiting, the function will throw. |
| [waitForTimeout](./puppeteer.page.waitfortimeout.md) | | |
| [waitForXPath](./puppeteer.page.waitforxpath.md) | | Wait for the <code>xpath</code> to appear in page. If at the moment of calling the method the <code>xpath</code> already exists, the method will return immediately. If the <code>xpath</code> doesn't appear after the <code>timeout</code> milliseconds of waiting, the function will throw. |
| [workers](./puppeteer.page.workers.md) | | All of the dedicated [WebWorkers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) associated with the page. |