Page class
Page provides methods to interact with a single tab or extension background page in Chromium. One Browser instance might have multiple Page instances.
This example creates a page, navigates it to a URL, and then saves a screenshot:
import 'dart:io';
import 'package:puppeteer/puppeteer.dart';
void main() async {
var browser = await puppeteer.launch();
var page = await browser.newPage();
await page.goto('https://example.com');
await File('screenshot.png').writeAsBytes(await page.screenshot());
await browser.close();
}
The Page class emits various events which can be handled using any of Dart' native Stream methods, such as listen, first, map, where...
page.onLoad.listen((_) => print('Page loaded!'));
To unsubscribe from events use the StreamSubscription.cancel method:
void logRequest(Request interceptedRequest) {
print('A request was made: ${interceptedRequest.url}');
}
var subscription = page.onRequest.listen(logRequest);
await subscription.cancel();
Properties
- accessibility → Accessibility
-
final
- browser → Browser
-
Get the browser the page belongs to.
no setter
- browserContext → BrowserContext
-
Get the browser context that the page belongs to.
no setter
-
content
→ Future<
String?> -
Gets the full HTML contents of the page, including the doctype.
no setter
- coverage → Coverage
-
final
-
Maximum navigation time in milliseconds
This setting will change the default maximum navigation time for the
following methods and related shortcuts:
getter/setter pair
- defaultTimeout ↔ Duration?
-
Maximum time in milliseconds
getter/setter pair
- devTools → DevTools
-
final
- frameManager → FrameManager
-
no setter
-
frames
→ List<
Frame> -
An array of all frames attached to the page.
no setter
- hashCode → int
-
The hash code for this object.
no setterinherited
- hasMainFrame → bool
-
no setter
- hasPopupListener → bool
-
no setter
- isClosed → bool
-
Indicates that the page has been closed.
no setter
- isDragInterceptionEnabled → bool
-
no setter
- javascriptEnabled → bool
-
no setter
- keyboard → Keyboard
-
no setter
- mainFrame → Frame
-
The page's main frame.
no setter
- mouse → Mouse
-
no setter
-
no setter
-
onClose
→ Future<
void> -
Complete when the page closes.
no setter
-
onConsole
→ Stream<
ConsoleMessage> -
Emitted when JavaScript within the page calls one of console API methods,
e.g. console.log or console.dir. Also emitted if the page throws an error
or a warning.
no setter
-
onDialog
→ Stream<
Dialog> -
Emitted when a JavaScript dialog appears, such as
alert,prompt,confirmorbeforeunload. Puppeteer can respond to the dialog via Dialog.accept or Dialog.dismiss methods.no setter -
onDomContentLoaded
→ Stream<
MonotonicTime> -
Emitted when the JavaScript
DOMContentLoadedevent is dispatched.no setter -
onError
→ Stream<
ClientError> -
Emitted when an uncaught exception happens within the page.
no setter
-
onFrameAttached
→ Stream<
Frame> -
Emitted when a frame is attached.
no setter
-
onFrameDetached
→ Stream<
Frame> -
Emitted when a frame is detached.
no setter
-
Emitted when a frame is navigated to a new url.
no setter
-
onLoad
→ Stream<
MonotonicTime> -
Emitted when the JavaScript
loadevent is dispatched.no setter -
onMetrics
→ Stream<
MetricsEvent> -
Emitted when the JavaScript code makes a call to
console.timeStamp. For the list of metrics seepage.metrics.no setter -
onPageCrashed
→ Stream<
void> -
Emitted when the page crashes.
no setter
-
onPopup
→ Stream<
Page> -
Emitted when the page opens a new tab or window.
no setter
-
onRequest
→ Stream<
Request> -
Emitted when a page issues a request.
In order to intercept and mutate requests, see Page.setRequestInterception.
no setter
-
onRequestFailed
→ Stream<
Request> -
Emitted when a request fails, for example by timing out.
no setter
-
onRequestFinished
→ Stream<
Request> -
Emitted when a request finishes successfully.
no setter
-
onResponse
→ Stream<
Response> -
Emitted when a
responseis received.no setter -
onWorkerCreated
→ Stream<
Worker> -
no setter
-
onWorkerDestroyed
→ Stream<
Worker> -
no setter
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
- session → Session
-
no setter
- target → Target
-
A target this page was created from.
final
-
title
→ Future<
String?> -
The page's title.
no setter
- touchscreen → Touchscreen
-
no setter
- tracing → Tracing
-
final
- url → String?
-
This is a shortcut for
page.mainFrame.urlno setter - viewport → DeviceViewport?
-
no setter
-
workers
→ List<
Worker> -
This method returns all of the dedicated WebWorkers
associated with the page.
no setter
Methods
-
$(
String selector) → Future< ElementHandle> -
The method runs
document.querySelectorwithin the page. If no element matches the selector, it throws an exception. If you know that no element may match use$OrNull(selector)which will returnnullif no element matches the selector. -
$$(
String selector) → Future< List< ElementHandle> > -
The method runs
document.querySelectorAllwithin the page. If no elements match the selector, the return value resolves to[]. -
$$eval<
T> (String selector, String pageFunction, {List? args}) → Future< T?> -
This method runs
Array.from(document.querySelectorAll(selector))within the page and passes it as the first argument topageFunction. -
$eval<
T> (String selector, String pageFunction, {List? args}) → Future< T?> -
This method runs
document.querySelectorwithin the page and passes it as the first argument topageFunction. If there's no element matchingselector, the method throws an error. -
$OrNull(
String selector) → Future< ElementHandle?> -
The method runs
document.querySelectorwithin the page. If no element matches the selector, the return value resolves tonull. -
$x(
String expression) → Future< List< ElementHandle> > - The method evaluates the XPath expression.
-
addScriptTag(
{String? url, File? file, String? content, String? type}) → Future< ElementHandle> -
Adds a
<script>tag into the page with the desired url or content. -
addStyleTag(
{String? url, File? file, String? content}) → Future< 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(
{String? username, String? password}) → Future< void> - Provide credentials for HTTP authentication.
-
bringToFront(
) → Future< void> - Brings page to front (activates tab).
-
click(
String selector, {Duration? delay, MouseButton? button, int? clickCount}) → Future< 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 matchingselector, the method throws an error. - Convenience function to wait for navigation to complete after clicking on an element.
-
close(
{bool? runBeforeUnload}) → Future< void> - By default, Page.close does not run beforeunload handlers.
- 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.
-
deleteCookie(
String name, {String? domain, String? path}) → Future< void> -
emitPopup(
Page popup) → void -
emulate(
Device device) → Future< void> - Emulates given device metrics and user agent. This method is a shortcut for calling two methods:
-
emulateMedia(
String? mediaType) → Future< void> -
emulateMediaFeatures(
List< MediaFeature> ? features) → Future<void> - Given an array of media feature objects, emulates CSS media features on the page.
-
emulateMediaType(
MediaType? mediaType) → Future< void> -
Changes the CSS media type of the page.
The only allowed values are
'screen','print'andnull. Passingnulldisables media emulation. -
emulateTimezone(
String timezoneId) → Future< void> -
evaluate<
T> (String pageFunction, {List? args}) → Future< T> -
If the function passed to the Page.evaluate returns a
Promise, then Page.evaluate would wait for the promise to resolve and return its value. -
evaluateHandle<
T extends JsHandle> (String pageFunction, {List? args}) → Future< T> - The only difference between Page.evaluate and Page.evaluateHandle is that Page.evaluateHandle returns in-page object (JSHandle).
-
evaluateOnNewDocument(
String pageFunction, {List? args}) → Future< void> - Adds a function which would be invoked in one of the following scenarios:
-
exposeFunction(
String name, Function callbackFunction) → Future< void> -
The method adds a function called
nameon the page'swindowobject. When called, the function executespuppeteerFunctionin Dart and returns aPromisewhich resolves to the return value ofpuppeteerFunction. -
focus(
String selector) → Future< void> -
This method fetches an element with
selectorand focuses it. If there's no element matchingselector, the method throws an error. -
goBack(
{Duration? timeout, Until? wait}) → Future< Response?> - Navigate to the previous page in history.
-
goForward(
{Duration? timeout, Until? wait}) → Future< Response?> - Navigate to the next page in history.
-
goto(
String url, {String? referrer, Duration? timeout, Until? wait}) → Future< Response> - The Page.goto will throw an error if:
-
hover(
String selector) → Future< 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 matchingselector, the method throws an error. -
metrics(
) → Future< Metrics> - Returns an object containing metrics of the page.
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
pdf(
{PaperFormat? format, num? scale, String? headerTemplate, bool? printBackground, bool? landscape, String? pageRanges, bool? preferCssPageSize, PdfMargins? margins, IOSink? output}) → Future< Uint8List?> -
Generates a pdf of the page with
printcss media. To generate a pdf withscreenmedia, call Page.emulateMedia('screen') before callingpage.pdf(): -
queryObjects(
JsHandle prototypeHandle) → Future< JsHandle> - The method iterates the JavaScript heap and finds all the objects with the given prototype.
-
reload(
{Duration? timeout, Until? wait}) → Future< Response> - Parameters:
-
screenshot(
{ScreenshotFormat? format, bool? fullPage, Rectangle< num> ? clip, int? quality, bool? omitBackground, bool? captureBeyondViewport, bool? fromSurface}) → Future<Uint8List> - Parameters:
-
screenshotBase64(
{ScreenshotFormat? format, bool? fullPage, Rectangle< num> ? clip, int? quality, bool? omitBackground, bool? captureBeyondViewport, bool? fromSurface}) → Future<String> - Parameters:
-
select(
String selector, List< String> values) → Future<List< String> > -
Triggers a
changeandinputevent once all the provided options have been selected. If there's no<select>element matchingselector, the method throws an error. -
setBypassCSP(
bool enabled) → Future< void> - Toggles bypassing page's Content-Security-Policy.
-
setCacheEnabled(
bool enabled) → Future< void> - Toggles ignoring cache for each request based on the enabled state. By default, caching is enabled.
-
setContent(
String html, {Duration? timeout, Until? wait}) → Future< void> - Parameters:
-
setCookies(
List< CookieParam> cookies) → Future<void> -
setDragInterception(
bool enabled) → Future< void> - @param enabled - Whether to enable drag interception.
-
setExtraHTTPHeaders(
Map< String, String> headers) → Future<void> - The extra HTTP headers will be sent with every request the page initiates.
-
setGeolocation(
{required num latitude, required num longitude, num? accuracy}) → Future< void> - Sets the page's geolocation.
-
setJavaScriptEnabled(
bool enabled) → Future< void> - Whether or not to enable JavaScript on the page.
-
setOfflineMode(
bool enabled) → Future< void> -
When
true, enables offline mode for the page. -
setRequestInterception(
bool value) → Future< void> - Whether to enable request interception.
-
setUserAgent(
String userAgent) → Future< void> - Specific user agent to use in this page
-
setViewport(
DeviceViewport viewport) → Future< void> -
NOTE in certain cases, setting viewport will reload the page in order to set the
isMobileorhasTouchproperties. -
tap(
String selector) → Future< void> -
This method fetches an element with
selector, scrolls it into view if needed, and then usespage.touchscreento tap in the center of the element. If there's no element matchingselector, the method throws an error. -
toString(
) → String -
A string representation of this object.
inherited
-
type(
String selector, String text, {Duration? delay}) → Future< void> -
Sends a
keydown,keypress/input, andkeyupevent for each character in the text. -
waitForFileChooser(
{Duration? timeout}) → Future< FileChooser> -
NOTE In non-headless Chromium, this method results in the native file picker dialog not showing up for the user.
-
waitForFrame(
bool predicate(Frame)) → Future< Frame> -
waitForFunction(
String pageFunction, {List? args, Duration? timeout, Polling? polling}) → Future< JsHandle> - Parameters:
- 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:
-
waitForRequest(
String url, {Duration? timeout}) → Future< Request> - Example:
-
waitForResponse(
String url, {Duration? timeout}) → Future< Response> -
waitForSelector(
String selector, {bool? visible, Duration? timeout}) → Future< ElementHandle?> -
Wait for the
selectorto appear in page. If at the moment of calling the method theselectoralready exists, the method will return immediately. If the selector doesn't appear after thetimeoutof waiting, the function will throw. -
waitForXPath(
String xpath, {bool? visible, Duration? timeout}) → Future< ElementHandle?> -
Wait for the
xpathto appear in page. If at the moment of calling the method thexpathalready exists, the method will return immediately. If the xpath doesn't appear after thetimeoutof waiting, the function will throw.
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited
Static Methods
-
create(
Target target, Session session, {DeviceViewport? viewport}) → Future< Page>