import { Page } from "https://deno.land/x/fresh@1.6.3/tests/deps.ts";
- Page provides methods to interact with a single tab or extension background page in Chromium.
-
::note
- One Browser instance might have multiple Page instances.
-
::
Examples
This example creates a page, navigates it to a URL, and then saves a screenshot:
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:
This example logs a message for a single page load
event:
page.once('load', () => console.log('Page loaded!'));
To unsubscribe from events use the Page.off method:
function logRequest(interceptedRequest) {
console.log('A request was made:', interceptedRequest.url());
}
page.on('request', logRequest);
// Sometime later...
page.off('request', logRequest);
Methods
Runs document.querySelector
within the page. If no element matches the
selector, the return value resolves to null
.
The method runs document.querySelectorAll
within the page. If no elements
match the selector, the return value resolves to []
.
This method runs Array.from(document.querySelectorAll(selector))
within
the page and passes the result as the first argument to the pageFunction
.
This method runs document.querySelector
within the page and passes the
result as the first argument to the pageFunction
.
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.
Adds a <script>
tag into the page with the desired URL or content.
Adds a <link rel="stylesheet">
tag into the page with the desired URL or a
<style type="text/css">
tag with the content.
Provide credentials for HTTP authentication
.
Brings page to front (activates tab).
Get the browser the page belongs to.
Get the browser context that the page belongs to.
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.
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.
Emulates given device metrics and user agent.
Enables CPU throttling to emulate slow CPUs.
Emulates the idle state. If no arguments set, clears idle state emulation.
Simulates the given vision deficiency on the page.
Evaluates a function in the page's context and returns the result.
If the function passed to page.evaluteHandle
returns a Promise, the
function will wait for the promise to resolve and return its value.
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
.
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. -
::note
This method fetches an element with selector
and focuses it. If there's no
element matching selector
, the method throws an error.
This method navigate to the previous page in history.
This method navigate to the next page in history.
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.
Indicates that the page has been closed.
- Listen to page events.
-
::note
- This method exists to define event typings and handle proper wireup of cooperative request interception. Actual event listening and dispatching is delegated to EventEmitter.
-
::
This method iterates the JavaScript heap and finds all objects with the given prototype.
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.
Toggles bypassing page's Content-Security-Policy.
Toggles ignoring cache for each request based on the enabled state. By default, caching is enabled.
- The 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.
-
::
Sets the page's geolocation.
Activating 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.
Enabling request interception disables page caching.
See the Request interception guide for more details.
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.
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.
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.
- This 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.
-
::
Waits for a function to finish evaluating in the page's context.
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();
})();
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();
})();