Page
Namespace: PuppeteerSharp
public abstract class Page : IPage, IDisposable, IAsyncDisposableSupports all classes in the .NET class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all .NET classes; it is the root of the type hierarchy.
Inheritance: object
Implements: IPage, IDisposable, IAsyncDisposable
Fields
Section titled “Fields”SupportedMetrics
Section titled “SupportedMetrics”public static readonly IEnumerable<string> SupportedMetricsList of supported metrics.
Value: IEnumerable<string>
Properties
Section titled “Properties”Browser
Section titled “Browser”protected abstract Browser Browser { get; }Browser.
Value: Browser
BrowserContext
Section titled “BrowserContext”public abstract IBrowserContext BrowserContext { get; }Get the browser context that the page belongs to.
Value: IBrowserContext
Client
Section titled “Client”public abstract CDPSession Client { get; }Supports all classes in the .NET class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all .NET classes; it is the root of the type hierarchy.
Value: CDPSession
DefaultNavigationTimeout
Section titled “DefaultNavigationTimeout”public int DefaultNavigationTimeout { get; set; }This setting will change the default maximum time for the following methods:
NavigationOptions)- GoBackAsync(NavigationOptions)
- GoForwardAsync(NavigationOptions)
- ReloadAsync(ReloadOptions)
NavigationOptions)- WaitForNavigationAsync(NavigationOptions) NOTE DefaultNavigationTimeout takes priority over. DefaultTimeout
Value: int
DefaultTimeout
Section titled “DefaultTimeout”public int DefaultTimeout { get; set; }This setting will change the default maximum times for the following methods:
- GoBackAsync(NavigationOptions)
- GoForwardAsync(NavigationOptions)
NavigationOptions)- ReloadAsync(ReloadOptions)
NavigationOptions)Object%5b%5d)- WaitForNavigationAsync(NavigationOptions)
WaitForOptions)WaitForOptions)WaitForSelectorOptions)WaitForFunctionOptions).
Value: int
Frames
Section titled “Frames”public abstract IFrame[] Frames { get; }Gets all frames attached to the page.
Value: IFrame\[\] — An array of all frames attached to the page.
HasConsoleEventListeners
Section titled “HasConsoleEventListeners”protected bool HasConsoleEventListeners { get; }Whether the Console event has listeners.
Value: bool
IsClosed
Section titled “IsClosed”public bool IsClosed { get; protected set; }Get an indication that the page has been closed.
Value: bool
IsDragInterceptionEnabled
Section titled “IsDragInterceptionEnabled”public bool IsDragInterceptionEnabled { get; protected set; }true if drag events are being intercepted, false otherwise.
Value: bool
IsJavaScriptEnabled
Section titled “IsJavaScriptEnabled”public abstract bool IsJavaScriptEnabled { get; }If the page has JavaScript enabled.
Value: bool
IsServiceWorkerBypassed
Section titled “IsServiceWorkerBypassed”public bool IsServiceWorkerBypassed { get; protected set; }true if the service worker are being bypassed.
Value: bool
MainFrame
Section titled “MainFrame”public abstract IFrame MainFrame { get; }Gets page’s main frame.
Value: IFrame
Page is guaranteed to have a main frame which persists during navigations.
ScreenshotBurstModeOn
Section titled “ScreenshotBurstModeOn”protected bool ScreenshotBurstModeOn { get; set; }Whether burst mode is on.
Value: bool
ScreenshotBurstModeOptions
Section titled “ScreenshotBurstModeOptions”protected ScreenshotOptions ScreenshotBurstModeOptions { get; set; }Screenshot burst mode options.
Value: ScreenshotOptions
Target
Section titled “Target”public abstract Target Target { get; }Supports all classes in the .NET class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all .NET classes; it is the root of the type hierarchy.
Value: Target
TimeoutSettings
Section titled “TimeoutSettings”public TimeoutSettings TimeoutSettings { get; set; }Timeout settings.
Value: TimeoutSettings
public string Url { get; }Shortcut for page.MainFrame.Url.
Value: string
Viewport
Section titled “Viewport”public ViewPortOptions Viewport { get; protected set; }Gets this page’s viewport.
Value: ViewPortOptions
WebMcp
Section titled “WebMcp”public virtual CdpWebMcp WebMcp { get; }Experimental API for WebMCP. Requires Chrome 149+ with –enable-features=WebMCPTesting,DevToolsWebMCPSupport flags enabled. Only supported with CDP protocol.
Value: CdpWebMcp
Exceptions
| Type | Condition |
|---|---|
| PuppeteerException | Thrown when not supported by the current browser/protocol. |
Workers
Section titled “Workers”public abstract WebWorker[] Workers { get; }Gets all workers in the page.
Value: WebWorker\[\]
Events
Section titled “Events”public event EventHandler CloseRaised when the page closes.
Value: EventHandler
Console
Section titled “Console”public event EventHandler<ConsoleEventArgs> ConsoleRaised 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.
The arguments passed into console.log appear as arguments on the event handler.
Value: EventHandler<ConsoleEventArgs>
Example
An example of handling Console event:
page.Console += (sender, e) =>{ for (var i = 0; i < e.Message.Args.Count; ++i) { System.Console.WriteLine($"{i}: {e.Message.Args[i]}"); }}DOMContentLoaded
Section titled “DOMContentLoaded”public event EventHandler DOMContentLoadedRaised when the JavaScript DOMContentLoaded <a href=“https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded">https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded</a> event is dispatched.
Value: EventHandler
Dialog
Section titled “Dialog”public event EventHandler<DialogEventArgs> DialogRaised when a JavaScript dialog appears, such as alert, prompt, confirm or beforeunload. Puppeteer can respond to the dialog via Dialog’s Accept(string) or Dismiss() methods.
Value: EventHandler<DialogEventArgs>
public event EventHandler<ErrorEventArgs> ErrorRaised when the page crashes
Value: EventHandler<ErrorEventArgs>
FrameAttached
Section titled “FrameAttached”public event EventHandler<FrameEventArgs> FrameAttachedRaised when a frame is attached.
Value: EventHandler<FrameEventArgs>
FrameDetached
Section titled “FrameDetached”public event EventHandler<FrameEventArgs> FrameDetachedRaised when a frame is detached.
Value: EventHandler<FrameEventArgs>
FrameNavigated
Section titled “FrameNavigated”public event EventHandler<FrameNavigatedEventArgs> FrameNavigatedRaised when a frame is navigated to a new url.
Value: EventHandler<FrameNavigatedEventArgs>
public event EventHandler<IssueEventArgs> IssueRaised when a DevTools issue is reported.
Value: EventHandler<IssueEventArgs>
public event EventHandler LoadRaised when the JavaScript load <a href=“https://developer.mozilla.org/en-US/docs/Web/Events/load">https://developer.mozilla.org/en-US/docs/Web/Events/load</a> event is dispatched.
Value: EventHandler
Metrics
Section titled “Metrics”public event EventHandler<MetricEventArgs> MetricsRaised when the JavaScript code makes a call to console.timeStamp. For the list of metrics see MetricsAsync().
Value: EventHandler<MetricEventArgs>
PageError
Section titled “PageError”public event EventHandler<PageErrorEventArgs> PageErrorRaised when an uncaught exception happens within the page.
Value: EventHandler<PageErrorEventArgs>
public event EventHandler<PopupEventArgs> PopupRaised when the page opens a new tab or window.
Value: EventHandler<PopupEventArgs>
Request
Section titled “Request”public event EventHandler<RequestEventArgs> RequestRaised when a page issues a request. The Request object is read-only. In order to intercept and mutate requests, see SetRequestInterceptionAsync(bool)
Value: EventHandler<RequestEventArgs>
RequestFailed
Section titled “RequestFailed”public event EventHandler<RequestEventArgs> RequestFailedRaised when a request fails, for example by timing out.
Value: EventHandler<RequestEventArgs>
RequestFinished
Section titled “RequestFinished”public event EventHandler<RequestEventArgs> RequestFinishedRaised when a request finishes successfully.
Value: EventHandler<RequestEventArgs>
RequestServedFromCache
Section titled “RequestServedFromCache”public event EventHandler<RequestEventArgs> RequestServedFromCacheRaised when a request ended up loading from cache.
Value: EventHandler<RequestEventArgs>
Response
Section titled “Response”public event EventHandler<ResponseCreatedEventArgs> ResponseRaised when a Response is received.
Value: EventHandler<ResponseCreatedEventArgs>
Example
An example of handling Response event:
var tcs = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);page.Response += async(sender, e) =>{ if (e.Response.Url.Contains("script.js")) { tcs.TrySetResult(await e.Response.TextAsync()); }};
await Task.WhenAll( page.GoToAsync(TestConstants.ServerUrl + "/grid.html"), tcs.Task);Console.WriteLine(await tcs.Task);WorkerCreated
Section titled “WorkerCreated”public event EventHandler<WorkerEventArgs> WorkerCreatedEmitted when a dedicated WebWorker (<a href=“https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API</a>) is spawned by the page.
Value: EventHandler<WorkerEventArgs>
WorkerDestroyed
Section titled “WorkerDestroyed”public event EventHandler<WorkerEventArgs> WorkerDestroyedEmitted when a dedicated WebWorker (<a href=“https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API</a>) is terminated.
Value: EventHandler<WorkerEventArgs>
Methods
Section titled “Methods”AddRequestInterceptor(Func<IRequest, Task>)
Section titled “AddRequestInterceptor(Func<IRequest, Task>)”public void AddRequestInterceptor(Func<IRequest, Task> interceptionTask)Int32%7d), Int32%7d), and Int32%7d) can accept an optional priority to activate Cooperative Intercept Mode.
In Cooperative Mode, all interception tasks are guaranteed to run and all async handlers are awaited.
The interception is resolved to the highest-priority resolution.
Parameters
| Name | Type | Description |
|---|---|---|
interceptionTask |
Func<IRequest, Task> | Interception task. |
AddScriptTagAsync(AddTagOptions)
Section titled “AddScriptTagAsync(AddTagOptions)”public Task<IElementHandle> AddScriptTagAsync(AddTagOptions options)Adds a <script> tag into the page with the desired url or content.
Parameters
| Name | Type | Description |
|---|---|---|
options |
AddTagOptions | add script tag options. |
Returns: Task<IElementHandle> — Task which resolves to the added tag when the script’s onload fires or when the script content was injected into frame.
Shortcut for page.MainFrame.AddScriptTagAsync(options).
AddScriptTagAsync(string)
Section titled “AddScriptTagAsync(string)”public Task<IElementHandle> AddScriptTagAsync(string url)Adds a <script> tag into the page with the desired url or content.
Parameters
| Name | Type | Description |
|---|---|---|
url |
string | script url. |
Returns: Task<IElementHandle> — Task which resolves to the added tag when the script’s onload fires or when the script content was injected into frame.
Shortcut for page.MainFrame.AddScriptTagAsync(new AddTagOptions { Url = url }).
AddStyleTagAsync(AddTagOptions)
Section titled “AddStyleTagAsync(AddTagOptions)”public Task<IElementHandle> AddStyleTagAsync(AddTagOptions options)Adds a <link rel="stylesheet"> tag into the page with the desired url or a <link rel="stylesheet"> tag with the content.
Parameters
| Name | Type | Description |
|---|---|---|
options |
AddTagOptions | add style tag options. |
Returns: Task<IElementHandle> — Task which resolves to the added tag when the stylesheet’s onload fires or when the CSS content was injected into frame.
Shortcut for page.MainFrame.AddStyleTagAsync(options).
AddStyleTagAsync(string)
Section titled “AddStyleTagAsync(string)”public Task<IElementHandle> AddStyleTagAsync(string url)Adds a <link rel="stylesheet"> tag into the page with the desired url or a <link rel="stylesheet"> tag with the content.
Parameters
| Name | Type | Description |
|---|---|---|
url |
string | stylesheet url. |
Returns: Task<IElementHandle> — Task which resolves to the added tag when the stylesheet’s onload fires or when the CSS content was injected into frame.
Shortcut for page.MainFrame.AddStyleTagAsync(new AddTagOptions { Url = url }).
AuthenticateAsync(Credentials)
Section titled “AuthenticateAsync(Credentials)”public abstract Task AuthenticateAsync(Credentials credentials)Provide credentials for http authentication <a href=“https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication">https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication</a>.
Parameters
| Name | Type | Description |
|---|---|---|
credentials |
Credentials | The credentials. |
Returns: Task — A Task which resolves after the message is sent to the browser.
To disable authentication, pass null.
BringToFrontAsync()
Section titled “BringToFrontAsync()”public abstract Task BringToFrontAsync()Brings page to front (activates tab).
Returns: Task — A task that resolves when the message has been sent to Chromium.
CaptureHeapSnapshotAsync(HeapSnapshotOptions)
Section titled “CaptureHeapSnapshotAsync(HeapSnapshotOptions)”public abstract Task CaptureHeapSnapshotAsync(HeapSnapshotOptions options)Captures a snapshot of the JavaScript heap and writes it to a file.
Parameters
| Name | Type | Description |
|---|---|---|
options |
HeapSnapshotOptions | Heap snapshot options. |
Returns: Task — A Task which resolves after the heap snapshot is captured and written to disk.
ClickAsync(string, ClickOptions)
Section titled “ClickAsync(string, ClickOptions)”public Task ClickAsync(string selector, ClickOptions options = null)Fetches an element with <code class=“paramref”>selector</code>, scrolls it into view if needed, and then uses Mouse to click in the center of the element.
Parameters
| Name | Type | Description |
|---|---|---|
selector |
string | A selector to search for element to click. If there are multiple elements satisfying the selector, the first will be clicked. |
options |
ClickOptions | click options. |
Returns: Task — Task which resolves when the element matching <code class=“paramref”>selector</code> is successfully clicked.
Exceptions
| Type | Condition |
|---|---|
| SelectorException | If there’s no element matching <code class=“paramref”>selector</code>. |
CloseAsync(PageCloseOptions)
Section titled “CloseAsync(PageCloseOptions)”public abstract Task CloseAsync(PageCloseOptions options = null)Closes the page.
Parameters
| Name | Type | Description |
|---|---|---|
options |
PageCloseOptions | Close options. |
Returns: Task — Task.
CreateCDPSessionAsync()
Section titled “CreateCDPSessionAsync()”public Task<ICDPSession> CreateCDPSessionAsync()Creates a Chrome Devtools Protocol session attached to the page.
Returns: Task<ICDPSession> — A task that returns a ICDPSession.
CreateScreenRecording(RecordOptions)
Section titled “CreateScreenRecording(RecordOptions)”protected abstract ScreenRecording CreateScreenRecording(RecordOptions options)Creates a protocol-specific screen recording instance.
Parameters
| Name | Type | Description |
|---|---|---|
options |
RecordOptions | Recording options. |
Returns: ScreenRecording — A screen recording instance.
DeleteCookieAsync(params CookieParam[])
Section titled “DeleteCookieAsync(params CookieParam[])”public abstract Task DeleteCookieAsync(params CookieParam[] cookies)Deletes cookies from the page.
Parameters
| Name | Type | Description |
|---|---|---|
cookies |
CookieParam\[\] |
Cookies to delete. |
Returns: Task — Task.
Dispose()
Section titled “Dispose()”public void Dispose()Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
Dispose(bool)
Section titled “Dispose(bool)”protected virtual void Dispose(bool disposing)Dispose resources.
Parameters
| Name | Type | Description |
|---|---|---|
disposing |
bool | Indicates whether disposal was initiated by Dispose() operation. |
DisposeAsync()
Section titled “DisposeAsync()”public ValueTask DisposeAsync()Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously.
Returns: ValueTask — A task that represents the asynchronous dispose operation.
EmulateAsync(DeviceDescriptor)
Section titled “EmulateAsync(DeviceDescriptor)”public Task EmulateAsync(DeviceDescriptor options)Emulates given device metrics and user agent.
Parameters
| Name | Type | Description |
|---|---|---|
options |
DeviceDescriptor | Emulation options. |
Returns: Task — Task.
This method is a shortcut for calling two methods:
SetViewportAsync(ViewPortOptions)
UserAgentMetadata)
To aid emulation, puppeteer provides a list of device descriptors which can be obtained via the Devices.
EmulateAsync(DeviceDescriptor) will resize the page. A lot of websites don’t expect phones to change size, so you should emulate before navigating to the page.
Example
var iPhone = Puppeteer.Devices[DeviceDescriptorName.IPhone6]; using(var page = await browser.NewPageAsync()) { await page.EmulateAsync(iPhone); await page.goto(‘https://www.google.com’); }
EmulateCPUThrottlingAsync(decimal?)
Section titled “EmulateCPUThrottlingAsync(decimal?)”public abstract Task EmulateCPUThrottlingAsync(decimal? factor = null)Enables CPU throttling to emulate slow CPUs.
Parameters
| Name | Type | Description |
|---|---|---|
factor |
decimal? | Throttling rate as a slowdown factor (1 is no throttle, 2 is 2x slowdown, etc). |
Returns: Task — A task that resolves when the message has been sent to the browser.
EmulateFocusedPageAsync(bool)
Section titled “EmulateFocusedPageAsync(bool)”public abstract Task EmulateFocusedPageAsync(bool enabled)Emulates focus state of the page.
Parameters
| Name | Type | Description |
|---|---|---|
enabled |
bool | Whether to emulate focus. |
Returns: Task — A task that resolves when the message has been sent to the browser.
EmulateIdleStateAsync(EmulateIdleOverrides)
Section titled “EmulateIdleStateAsync(EmulateIdleOverrides)”public abstract Task EmulateIdleStateAsync(EmulateIdleOverrides idleOverrides = null)Emulates the idle state. If no arguments set, clears idle state emulation.
Parameters
| Name | Type | Description |
|---|---|---|
idleOverrides |
EmulateIdleOverrides | Overrides. |
Returns: Task — A task that resolves when the message has been sent to the browser.
Example
// set idle emulationawait page.EmulateIdleStateAsync(new EmulateIdleOverrides() {IsUserActive = true, IsScreenUnlocked = false});// do some checks here...// clear idle emulationawait page.EmulateIdleStateAsync();EmulateLocaleAsync(string)
Section titled “EmulateLocaleAsync(string)”public abstract Task EmulateLocaleAsync(string locale = null)Emulates the locale of the page.
Parameters
| Name | Type | Description |
|---|---|---|
locale |
string | Locale to emulate on the page (e.g., “en-US”, “de-DE”). Passing null disables locale emulation. |
Returns: Task — A task that resolves when the locale has been set.
EmulateMediaFeaturesAsync(IEnumerable<MediaFeatureValue>)
Section titled “EmulateMediaFeaturesAsync(IEnumerable<MediaFeatureValue>)”public abstract Task EmulateMediaFeaturesAsync(IEnumerable<MediaFeatureValue> features)Given an array of media feature objects, emulates CSS media features on the page.
Parameters
| Name | Type | Description |
|---|---|---|
features |
IEnumerable<MediaFeatureValue> | Features to apply. |
Returns: Task — Emulate features task.
Example
await page.EmulateMediaFeaturesAsync(new MediaFeature[]{ new MediaFeature { MediaFeature = MediaFeature.PrefersColorScheme, Value = "dark" }});await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: dark)').matches)");// → trueawait page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: light)').matches)");// → falseawait page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");// → falseawait page.EmulateMediaFeaturesAsync(new MediaFeature[]{ new MediaFeature { MediaFeature = MediaFeature.PrefersReducedMotion, Value = "reduce" }});await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-reduced-motion: reduce)').matches)");// → trueawait page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");// → falseawait page.EmulateMediaFeaturesAsync(new MediaFeature[]{ new MediaFeature { MediaFeature = MediaFeature.PrefersColorScheme, Value = "dark" }, new MediaFeature { MediaFeature = MediaFeature.PrefersReducedMotion, Value = "reduce" },});await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: dark)').matches)");// → trueawait page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: light)').matches)");// → falseawait page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");// → falseawait page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-reduced-motion: reduce)').matches)");// → trueawait page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");// → falseEmulateMediaTypeAsync(MediaType)
Section titled “EmulateMediaTypeAsync(MediaType)”public abstract Task EmulateMediaTypeAsync(MediaType type)Emulates a media such as screen or print.
Parameters
| Name | Type | Description |
|---|---|---|
type |
MediaType | Media to set. |
Returns: Task — Emulate media type task.
Example
await page.EvaluateFunctionAsync<bool>("() => matchMedia('screen').matches)");// → trueawait page.EvaluateFunctionAsync<bool>("() => matchMedia('print').matches)");// → trueawait page.EmulateMediaTypeAsync(MediaType.Print);await page.EvaluateFunctionAsync<bool>("() => matchMedia('screen').matches)");// → falseawait page.EvaluateFunctionAsync<bool>("() => matchMedia('print').matches)");// → trueawait page.EmulateMediaTypeAsync(MediaType.None);await page.EvaluateFunctionAsync<bool>("() => matchMedia('screen').matches)");// → trueawait page.EvaluateFunctionAsync<bool>("() => matchMedia('print').matches)");// → trueEmulateNetworkConditionsAsync(NetworkConditions)
Section titled “EmulateNetworkConditionsAsync(NetworkConditions)”public abstract Task EmulateNetworkConditionsAsync(NetworkConditions networkConditions)Emulates network conditions.
Parameters
| Name | Type | Description |
|---|---|---|
networkConditions |
NetworkConditions | Passing null disables network condition emulation. |
Returns: Task — Result task.
NOTE This does not affect WebSockets and WebRTC PeerConnections (see https://crbug.com/563644).
EmulateTimezoneAsync(string)
Section titled “EmulateTimezoneAsync(string)”public abstract Task EmulateTimezoneAsync(string timezoneId)Changes the timezone of the page.
Parameters
| Name | Type | Description |
|---|---|---|
timezoneId |
string | Timezone to set. See <a href=“https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1">ICU’s metaZones.txt</a> for a list of supported timezone IDs. Passing null disables timezone emulation. |
Returns: Task — The viewport task.
EmulateVisionDeficiencyAsync(VisionDeficiency)
Section titled “EmulateVisionDeficiencyAsync(VisionDeficiency)”public abstract Task EmulateVisionDeficiencyAsync(VisionDeficiency type)Simulates the given vision deficiency on the page.
Parameters
| Name | Type | Description |
|---|---|---|
type |
VisionDeficiency | The type of deficiency to simulate, or None to reset. |
Returns: Task — A task that resolves when the message has been sent to the browser.
Example
await Page.EmulateVisionDeficiencyAsync(VisionDeficiency.Achromatopsia); await Page.ScreenshotAsync(“Achromatopsia.png”).
EvaluateExpressionAsync(string)
Section titled “EvaluateExpressionAsync(string)”public Task EvaluateExpressionAsync(string script)Executes a script in browser context.
Parameters
| Name | Type | Description |
|---|---|---|
script |
string | Script to be evaluated in browser context. |
Returns: Task — Task which resolves to script return value.
If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.
Example
An example of scraping information from all hyperlinks on the page.
var hyperlinkInfo = await page.EvaluateExpressionAsync(@" Array .from(document.querySelectorAll('a')) .map(n => ({ text: n.innerText, href: n.getAttribute('href'), target: n.getAttribute('target') }))");Console.WriteLine(hyperlinkInfo.ToString()); // Displays JSON array of hyperlinkInfo objectsEvaluateExpressionAsync<T>(string)
Section titled “EvaluateExpressionAsync<T>(string)”public Task<T> EvaluateExpressionAsync<T>(string script)Executes a script in browser context.
Type parameters
| Name | Description |
|---|---|
T |
The type to deserialize the result to. |
Parameters
| Name | Type | Description |
|---|---|---|
script |
string | Script to be evaluated in browser context. |
Returns: Task<T> — Task which resolves to script return value.
If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.
EvaluateExpressionHandleAsync(string)
Section titled “EvaluateExpressionHandleAsync(string)”public Task<IJSHandle> EvaluateExpressionHandleAsync(string script)Executes a script in browser context.
Parameters
| Name | Type | Description |
|---|---|---|
script |
string | Script to be evaluated in browser context. |
Returns: Task<IJSHandle> — Task which resolves to script return value.
If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.
EvaluateExpressionOnNewDocumentAsync(string)
Section titled “EvaluateExpressionOnNewDocumentAsync(string)”public abstract Task<NewDocumentScriptEvaluation> EvaluateExpressionOnNewDocumentAsync(string expression)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.
Parameters
| Name | Type | Description |
|---|---|---|
expression |
string | Javascript expression to be evaluated in browser context. |
Returns: Task<NewDocumentScriptEvaluation> — Task.
The function is invoked after the document was created but before any of its scripts were run. This is useful to amend JavaScript environment, e.g. to seed Math.random.
Example
An example of overriding the navigator.languages property before the page loads:
await page.EvaluateExpressionOnNewDocumentAsync("window.__example = true;");EvaluateFunctionAsync(string, params object[])
Section titled “EvaluateFunctionAsync(string, params object[])”public Task EvaluateFunctionAsync(string script, params object[] args)Executes a function in browser context.
Parameters
| Name | Type | Description |
|---|---|---|
script |
string | Script to be evaluated in browser context. |
args |
object[] | Arguments to pass to script. |
Returns: Task — Task which resolves to script return value.
If the script, returns a Promise, then the method would wait for the promise to resolve and return its value. IJSHandle instances can be passed as arguments.
EvaluateFunctionAsync<T>(string, params object[])
Section titled “EvaluateFunctionAsync<T>(string, params object[])”public Task<T> EvaluateFunctionAsync<T>(string script, params object[] args)Executes a function in browser context.
Type parameters
| Name | Description |
|---|---|
T |
The type to deserialize the result to. |
Parameters
| Name | Type | Description |
|---|---|---|
script |
string | Script to be evaluated in browser context. |
args |
object[] | Arguments to pass to script. |
Returns: Task<T> — Task which resolves to script return value.
If the script, returns a Promise, then the method would wait for the promise to resolve and return its value. IJSHandle instances can be passed as arguments.
EvaluateFunctionHandleAsync(string, params object[])
Section titled “EvaluateFunctionHandleAsync(string, params object[])”public Task<IJSHandle> EvaluateFunctionHandleAsync(string pageFunction, params object[] args)Executes a script in browser context.
Parameters
| Name | Type | Description |
|---|---|---|
pageFunction |
string | Script to be evaluated in browser context. |
args |
object[] | Function arguments. |
Returns: Task<IJSHandle> — Task which resolves to script return value.
If the script, returns a Promise, then the method would wait for the promise to resolve and return its value. IJSHandle instances can be passed as arguments.
EvaluateFunctionOnNewDocumentAsync(string, params object[])
Section titled “EvaluateFunctionOnNewDocumentAsync(string, params object[])”public abstract Task<NewDocumentScriptEvaluation> EvaluateFunctionOnNewDocumentAsync(string pageFunction, params object[] args)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.
Parameters
| Name | Type | Description |
|---|---|---|
pageFunction |
string | Function to be evaluated in browser context. |
args |
object[] | Arguments to pass to pageFunction. |
Returns: Task<NewDocumentScriptEvaluation> — Task.
The function is invoked after the document was created but before any of its scripts were run. This is useful to amend JavaScript environment, e.g. to seed Math.random.
Example
An example of overriding the navigator.languages property before the page loads:
await page.EvaluateFunctionOnNewDocumentAsync("() => window.__example = true");ExposeFunctionAsync(string, Action)
Section titled “ExposeFunctionAsync(string, Action)”public Task ExposeFunctionAsync(string name, Action puppeteerFunction)Adds a function called name on the page’s window object.
When called, the function executes <code class=“paramref”>puppeteerFunction</code> in C# and returns a Task which resolves when <code class=“paramref”>puppeteerFunction</code> completes.
Parameters
| Name | Type | Description |
|---|---|---|
name |
string | Name of the function on the window object. |
puppeteerFunction |
Action | Callback function which will be called in Puppeteer’s context. |
Returns: Task — Task.
If the <code class=“paramref”>puppeteerFunction</code> returns a Task, it will be awaited.
Functions installed via Action) survive navigations.
ExposeFunctionAsync(string, Delegate)
Section titled “ExposeFunctionAsync(string, Delegate)”protected abstract Task ExposeFunctionAsync(string name, Delegate puppeteerFunction)Internal add exposed functions.
Parameters
| Name | Type | Description |
|---|---|---|
name |
string | Function name. |
puppeteerFunction |
Delegate | Puppeteer function. |
Returns: Task — A Task that completes when the function has been added.
ExposeFunctionAsync<TResult>(string, Func<TResult>)
Section titled “ExposeFunctionAsync<TResult>(string, Func<TResult>)”public Task ExposeFunctionAsync<TResult>(string name, Func<TResult> puppeteerFunction)Adds a function called name on the page’s window object.
When called, the function executes <code class=“paramref”>puppeteerFunction</code> in C# and returns a Task which resolves to the return value of <code class=“paramref”>puppeteerFunction</code>.
Type parameters
| Name | Description |
|---|---|
TResult |
The result of <code class=“paramref”>puppeteerFunction</code>. |
Parameters
| Name | Type | Description |
|---|---|---|
name |
string | Name of the function on the window object. |
puppeteerFunction |
Func<TResult> | Callback function which will be called in Puppeteer’s context. |
Returns: Task — Task.
If the <code class=“paramref”>puppeteerFunction</code> returns a Task, it will be awaited.
Functions installed via Func%7b%60%600%7d) survive navigations.
ExposeFunctionAsync<T, TResult>(string, Func<T, TResult>)
Section titled “ExposeFunctionAsync<T, TResult>(string, Func<T, TResult>)”public Task ExposeFunctionAsync<T, TResult>(string name, Func<T, TResult> puppeteerFunction)Adds a function called name on the page’s window object.
When called, the function executes <code class=“paramref”>puppeteerFunction</code> in C# and returns a Task which resolves to the return value of <code class=“paramref”>puppeteerFunction</code>.
Type parameters
| Name | Description |
|---|---|
T |
The parameter of <code class=“paramref”>puppeteerFunction</code>. |
TResult |
The result of <code class=“paramref”>puppeteerFunction</code>. |
Parameters
| Name | Type | Description |
|---|---|---|
name |
string | Name of the function on the window object. |
puppeteerFunction |
Func<T, TResult> | Callback function which will be called in Puppeteer’s context. |
Returns: Task — Task.
If the <code class=“paramref”>puppeteerFunction</code> returns a Task, it will be awaited.
Functions installed via Func%7b%60%600%2c%60%601%7d) survive navigations.
ExposeFunctionAsync<T1, T2, TResult>(string, Func<T1, T2, TResult>)
Section titled “ExposeFunctionAsync<T1, T2, TResult>(string, Func<T1, T2, TResult>)”public Task ExposeFunctionAsync<T1, T2, TResult>(string name, Func<T1, T2, TResult> puppeteerFunction)Adds a function called name on the page’s window object.
When called, the function executes <code class=“paramref”>puppeteerFunction</code> in C# and returns a Task which resolves to the return value of <code class=“paramref”>puppeteerFunction</code>.
Type parameters
| Name | Description |
|---|---|
T1 |
The first parameter of <code class=“paramref”>puppeteerFunction</code>. |
T2 |
The second parameter of <code class=“paramref”>puppeteerFunction</code>. |
TResult |
The result of <code class=“paramref”>puppeteerFunction</code>. |
Parameters
| Name | Type | Description |
|---|---|---|
name |
string | Name of the function on the window object. |
puppeteerFunction |
Func<T1, T2, TResult> | Callback function which will be called in Puppeteer’s context. |
Returns: Task — Task.
If the <code class=“paramref”>puppeteerFunction</code> returns a Task, it will be awaited.
Functions installed via Func%7b%60%600%2c%60%601%2c%60%602%7d) survive navigations.
ExposeFunctionAsync<T1, T2, T3, TResult>(string, Func<T1, T2, T3, TResult>)
Section titled “ExposeFunctionAsync<T1, T2, T3, TResult>(string, Func<T1, T2, T3, TResult>)”public Task ExposeFunctionAsync<T1, T2, T3, TResult>(string name, Func<T1, T2, T3, TResult> puppeteerFunction)Adds a function called name on the page’s window object.
When called, the function executes <code class=“paramref”>puppeteerFunction</code> in C# and returns a Task which resolves to the return value of <code class=“paramref”>puppeteerFunction</code>.
Type parameters
| Name | Description |
|---|---|
T1 |
The first parameter of <code class=“paramref”>puppeteerFunction</code>. |
T2 |
The second parameter of <code class=“paramref”>puppeteerFunction</code>. |
T3 |
The third parameter of <code class=“paramref”>puppeteerFunction</code>. |
TResult |
The result of <code class=“paramref”>puppeteerFunction</code>. |
Parameters
| Name | Type | Description |
|---|---|---|
name |
string | Name of the function on the window object. |
puppeteerFunction |
Func<T1, T2, T3, TResult> | Callback function which will be called in Puppeteer’s context. |
Returns: Task — Task.
If the <code class=“paramref”>puppeteerFunction</code> returns a Task, it will be awaited.
Functions installed via Func%7b%60%600%2c%60%601%2c%60%602%2c%60%603%7d) survive navigations.
ExposeFunctionAsync<T1, T2, T3, T4, TResult>(string, Func<T1, T2, T3, T4, TResult>)
Section titled “ExposeFunctionAsync<T1, T2, T3, T4, TResult>(string, Func<T1, T2, T3, T4, TResult>)”public Task ExposeFunctionAsync<T1, T2, T3, T4, TResult>(string name, Func<T1, T2, T3, T4, TResult> puppeteerFunction)Adds a function called name on the page’s window object.
When called, the function executes <code class=“paramref”>puppeteerFunction</code> in C# and returns a Task which resolves to the return value of <code class=“paramref”>puppeteerFunction</code>.
Type parameters
| Name | Description |
|---|---|
T1 |
The first parameter of <code class=“paramref”>puppeteerFunction</code>. |
T2 |
The second parameter of <code class=“paramref”>puppeteerFunction</code>. |
T3 |
The third parameter of <code class=“paramref”>puppeteerFunction</code>. |
T4 |
The fourth parameter of <code class=“paramref”>puppeteerFunction</code>. |
TResult |
The result of <code class=“paramref”>puppeteerFunction</code>. |
Parameters
| Name | Type | Description |
|---|---|---|
name |
string | Name of the function on the window object. |
puppeteerFunction |
Func<T1, T2, T3, T4, TResult> | Callback function which will be called in Puppeteer’s context. |
Returns: Task — Task.
If the <code class=“paramref”>puppeteerFunction</code> returns a Task, it will be awaited.
Functions installed via Func%7b%60%600%2c%60%601%2c%60%602%2c%60%603%2c%60%604%7d) survive navigations.
ExtensionRealms()
Section titled “ExtensionRealms()”public abstract IReadOnlyList<Realm> ExtensionRealms()Retrieves the list of extension realms inside the main frame of this page.
Shortcut for MainFrame.ExtensionRealms().
Returns: IReadOnlyList<Realm> — A list of Realm instances representing extension execution contexts.
FocusAsync(string)
Section titled “FocusAsync(string)”public Task FocusAsync(string selector)Fetches an element with <code class=“paramref”>selector</code> and focuses it.
Parameters
| Name | Type | Description |
|---|---|---|
selector |
string | A selector to search for element to focus. If there are multiple elements satisfying the selector, the first will be focused. |
Returns: Task — Task which resolves when the element matching <code class=“paramref”>selector</code> is successfully focused.
Exceptions
| Type | Condition |
|---|---|
| SelectorException | If there’s no element matching <code class=“paramref”>selector</code>. |
GetContentAsync(GetContentOptions)
Section titled “GetContentAsync(GetContentOptions)”public Task<string> GetContentAsync(GetContentOptions options = null)Gets the full HTML contents of the page, including the doctype.
Parameters
| Name | Type | Description |
|---|---|---|
options |
GetContentOptions | Options. |
Returns: Task<string> — Task which resolves to the HTML content.
GetCookiesAsync(params string[])
Section titled “GetCookiesAsync(params string[])”public abstract Task<CookieParam[]> GetCookiesAsync(params string[] urls)Returns the page’s cookies.
Parameters
| Name | Type | Description |
|---|---|---|
urls |
string[] | Url’s to return cookies for. |
Returns: Task<CookieParam[]> — Array of cookies.
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.
GetTitleAsync()
Section titled “GetTitleAsync()”public Task<string> GetTitleAsync()Returns page’s title.
Returns: Task<string> — page’s title.
GoBackAsync(NavigationOptions)
Section titled “GoBackAsync(NavigationOptions)”public abstract Task<IResponse> GoBackAsync(NavigationOptions options = null)Navigate to the previous page in history.
Parameters
| Name | Type | Description |
|---|---|---|
options |
NavigationOptions | Navigation parameters. |
Returns: Task<IResponse> — Task that 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.
GoForwardAsync(NavigationOptions)
Section titled “GoForwardAsync(NavigationOptions)”public abstract Task<IResponse> GoForwardAsync(NavigationOptions options = null)Navigate to the next page in history.
Parameters
| Name | Type | Description |
|---|---|---|
options |
NavigationOptions | Navigation parameters. |
Returns: Task<IResponse> — Task that 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.
GoToAsync(string, NavigationOptions)
Section titled “GoToAsync(string, NavigationOptions)”public Task<IResponse> GoToAsync(string url, NavigationOptions options)Navigates to an url.
Parameters
| Name | Type | Description |
|---|---|---|
url |
string | URL to navigate page to. The url should include scheme, e.g. https://. |
options |
NavigationOptions | Navigation parameters. |
Returns: Task<IResponse> — Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
WaitUntilNavigation%5b%5d) will throw an error if:
- there’s an SSL error (e.g. in case of self-signed certificates).
- target URL is invalid.
- the
timeoutis exceeded during navigation. - the remote server does not respond or is unreachable.
- the main resource failed to load.
WaitUntilNavigation%5b%5d) will not throw an error when any valid HTTP status code is returned by the remote server,
including 404 “Not Found” and 500 “Internal Server Error”. The status code for such responses can be retrieved by calling Status
> NOTE WaitUntilNavigation%5b%5d) either throws an error or returns a main resource response.
The only exceptions are navigation to about:blank or navigation to the same URL with a different hash, which would succeed and return null.
> NOTE Headless mode doesn’t support navigation to a PDF document. See the <see fref=“https://bugs.chromium.org/p/chromium/issues/detail?id=761295">upstream issue</see>.
Shortcut for. WaitUntilNavigation%5b%5d)
GoToAsync(string, WaitUntilNavigation)
Section titled “GoToAsync(string, WaitUntilNavigation)”public Task<IResponse> GoToAsync(string url, WaitUntilNavigation waitUntil)Navigates to an url.
Parameters
| Name | Type | Description |
|---|---|---|
url |
string | URL to navigate page to. The url should include scheme, e.g. https://. |
waitUntil |
WaitUntilNavigation | When to consider navigation succeeded. |
Returns: Task<IResponse> — Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
GoToAsync(string, int?, WaitUntilNavigation[])
Section titled “GoToAsync(string, int?, WaitUntilNavigation[])”public Task<IResponse> GoToAsync(string url, int? timeout = null, WaitUntilNavigation[] waitUntil = null)Navigates to an url.
Parameters
| Name | Type | Description |
|---|---|---|
url |
string | URL to navigate page to. The url should include scheme, e.g. https://. |
timeout |
int? | Maximum navigation time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. |
waitUntil |
WaitUntilNavigation\[\] |
When to consider navigation succeeded, defaults to Load. Given an array of WaitUntilNavigation, navigation is considered to be successful after all events have been fired. |
Returns: Task<IResponse> — Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
HasDevToolsAsync()
Section titled “HasDevToolsAsync()”public abstract Task<bool> HasDevToolsAsync()Returns true if DevTools is attached to the current page. Use OpenDevToolsAsync() to get the DevTools page.
Returns: Task<bool> — A Task%601 that completes with true if DevTools is attached.
HoverAsync(string)
Section titled “HoverAsync(string)”public Task HoverAsync(string selector)Fetches an element with <code class=“paramref”>selector</code>, scrolls it into view if needed, and then uses Mouse to hover over the center of the element.
Parameters
| Name | Type | Description |
|---|---|---|
selector |
string | A selector to search for element to hover. If there are multiple elements satisfying the selector, the first will be hovered. |
Returns: Task — Task which resolves when the element matching <code class=“paramref”>selector</code> is successfully hovered.
Exceptions
| Type | Condition |
|---|---|
| SelectorException | If there’s no element matching <code class=“paramref”>selector</code>. |
Locator(string)
Section titled “Locator(string)”public Locator Locator(string selector)Creates a locator for the provided selector. See Locator for details and supported actions.
Parameters
| Name | Type | Description |
|---|---|---|
selector |
string | A selector to locate an element. |
Returns: Locator — A locator for the provided selector.
LocatorFunction(string)
Section titled “LocatorFunction(string)”public Locator LocatorFunction(string func)Creates a locator for the provided function. See Locator for details and supported actions.
Parameters
| Name | Type | Description |
|---|---|---|
func |
string | A JavaScript function expression to evaluate. |
Returns: Locator — A locator for the provided function.
MetricsAsync()
Section titled “MetricsAsync()”public abstract Task<Dictionary<string, decimal>> MetricsAsync()Returns metrics.
Returns: Task<Dictionary<string, decimal>> — Task which resolves into a list of metrics.
All timestamps are in monotonic time: monotonically increasing time in seconds since an arbitrary point in the past.
OnClose()
Section titled “OnClose()”protected void OnClose()Raises the Close event.
OnConsole(ConsoleEventArgs)
Section titled “OnConsole(ConsoleEventArgs)”protected void OnConsole(ConsoleEventArgs e)Raises the Console event.
Parameters
| Name | Type | Description |
|---|---|---|
e |
ConsoleEventArgs | Event args. |
OnError(ErrorEventArgs)
Section titled “OnError(ErrorEventArgs)”protected void OnError(ErrorEventArgs e)Raises the Error event.
Parameters
| Name | Type | Description |
|---|---|---|
e |
ErrorEventArgs | Event args. |
OnMetrics(MetricEventArgs)
Section titled “OnMetrics(MetricEventArgs)”protected void OnMetrics(MetricEventArgs e)Raises the Metrics event.
Parameters
| Name | Type | Description |
|---|---|---|
e |
MetricEventArgs | Event args. |
OnPageError(PageErrorEventArgs)
Section titled “OnPageError(PageErrorEventArgs)”protected void OnPageError(PageErrorEventArgs e)Raises the PageError event.
Parameters
| Name | Type | Description |
|---|---|---|
e |
PageErrorEventArgs | Event args. |
OnWorkerCreated(WebWorker)
Section titled “OnWorkerCreated(WebWorker)”protected void OnWorkerCreated(WebWorker worker)Raises the WorkerCreated event.
Parameters
| Name | Type | Description |
|---|---|---|
worker |
WebWorker | Worker. |
OnWorkerDestroyed(WebWorker)
Section titled “OnWorkerDestroyed(WebWorker)”protected void OnWorkerDestroyed(WebWorker worker)Raises the WorkerDestroyed event.
Parameters
| Name | Type | Description |
|---|---|---|
worker |
WebWorker | Worker. |
OpenDevToolsAsync()
Section titled “OpenDevToolsAsync()”public abstract Task<IPage> OpenDevToolsAsync()Opens DevTools for this page if not already open and returns the DevTools page. This method is only available in Chrome.
Returns: Task<IPage> — A Task%601 that completes with the DevTools page.
PdfAsync(string)
Section titled “PdfAsync(string)”public Task PdfAsync(string file)generates a pdf of the page with Print css media. To generate a pdf with Screen media call EmulateMediaTypeAsync(MediaType) with Screen.
Parameters
| Name | Type | Description |
|---|---|---|
file |
string | The file path to save the PDF to. paths are resolved using GetFullPath(string). |
Returns: Task — A Task which resolves after the PDF is generated.
Generating a pdf is currently only supported in Chrome headless.
PdfAsync(string, PdfOptions)
Section titled “PdfAsync(string, PdfOptions)”public Task PdfAsync(string file, PdfOptions options)generates a pdf of the page with Print css media. To generate a pdf with Screen media call EmulateMediaTypeAsync(MediaType) with Screen.
Parameters
| Name | Type | Description |
|---|---|---|
file |
string | The file path to save the PDF to. paths are resolved using GetFullPath(string). |
options |
PdfOptions | pdf options. |
Returns: Task — A Task which resolves after the PDF is generated.
Generating a pdf is currently only supported in Chrome headless.
PdfDataAsync()
Section titled “PdfDataAsync()”public Task<byte[]> PdfDataAsync()Generates a pdf of the page with Print css media. To generate a pdf with Screen media call EmulateMediaTypeAsync(MediaType) with Screen.
Returns: Task<byte[]> — Task which resolves to a byte[] containing the PDF data.
Generating a pdf is currently only supported in Chrome headless.
PdfDataAsync(PdfOptions)
Section titled “PdfDataAsync(PdfOptions)”public Task<byte[]> PdfDataAsync(PdfOptions options)Generates a pdf of the page with Print css media. To generate a pdf with Screen media call EmulateMediaTypeAsync(MediaType) with Screen.
Parameters
| Name | Type | Description |
|---|---|---|
options |
PdfOptions | pdf options. |
Returns: Task<byte[]> — Task which resolves to a byte[] containing the PDF data.
Generating a pdf is currently only supported in Chrome headless.
PdfInternalAsync(Stream, PdfOptions)
Section titled “PdfInternalAsync(Stream, PdfOptions)”protected abstract Task PdfInternalAsync(Stream outputStream, PdfOptions options)PDF implementation.
Parameters
| Name | Type | Description |
|---|---|---|
outputStream |
Stream | Where to write the PDF bytes. |
options |
PdfOptions | PDF options. |
Returns: Task — PDF data.
PdfStreamAsync()
Section titled “PdfStreamAsync()”public Task<Stream> PdfStreamAsync()generates a pdf of the page with Print css media. To generate a pdf with Screen media call EmulateMediaTypeAsync(MediaType) with Screen.
Returns: Task<Stream> — Task which resolves to a Stream containing the PDF data.
Generating a pdf is currently only supported in Chrome headless.
PdfStreamAsync(PdfOptions)
Section titled “PdfStreamAsync(PdfOptions)”public Task<Stream> PdfStreamAsync(PdfOptions options)Generates a pdf of the page with Print css media. To generate a pdf with Screen media call EmulateMediaTypeAsync(MediaType) with Screen.
Parameters
| Name | Type | Description |
|---|---|---|
options |
PdfOptions | pdf options. |
Returns: Task<Stream> — Task which resolves to a Stream containing the PDF data.
Generating a pdf is currently only supported in Chrome headless.
PerformScreenshotAsync(ScreenshotType, ScreenshotOptions)
Section titled “PerformScreenshotAsync(ScreenshotType, ScreenshotOptions)”protected abstract Task<string> PerformScreenshotAsync(ScreenshotType type, ScreenshotOptions options)Screenshot implementation.
Parameters
| Name | Type | Description |
|---|---|---|
type |
ScreenshotType | Screenshot type. |
options |
ScreenshotOptions | Options. |
Returns: Task<string> — The screenshot as a base64 string.
QueryObjectsAsync(IJSHandle)
Section titled “QueryObjectsAsync(IJSHandle)”public abstract Task<IJSHandle> QueryObjectsAsync(IJSHandle prototypeHandle)The method iterates JavaScript heap and finds all the objects with the given prototype.
Shortcut for page.MainFrame.GetExecutionContextAsync().QueryObjectsAsync(prototypeHandle).
Parameters
| Name | Type | Description |
|---|---|---|
prototypeHandle |
IJSHandle | A handle to the object prototype. |
Returns: Task<IJSHandle> — A task which resolves to a handle to an array of objects with this prototype.
QuerySelectorAllAsync(string)
Section titled “QuerySelectorAllAsync(string)”public Task<IElementHandle[]> QuerySelectorAllAsync(string selector)Runs document.querySelectorAll within the page. If no elements match the selector, the return value resolve to Empty%60%601.
Parameters
| Name | Type | Description |
|---|---|---|
selector |
string | A selector to query page for. |
Returns: Task<IElementHandle[]> — Task which resolves to ElementHandles pointing to the frame elements.
QuerySelectorAllAsync(string, QueryOptions)
Section titled “QuerySelectorAllAsync(string, QueryOptions)”public Task<IElementHandle[]> QuerySelectorAllAsync(string selector, QueryOptions options)Runs document.querySelectorAll within the page. If no elements match the selector, the return value resolve to Empty%60%601.
Parameters
| Name | Type | Description |
|---|---|---|
selector |
string | A selector to query page for. |
options |
QueryOptions | Optional query options. |
Returns: Task<IElementHandle[]> — Task which resolves to ElementHandles pointing to the frame elements.
QuerySelectorAllHandleAsync(string)
Section titled “QuerySelectorAllHandleAsync(string)”public Task<IJSHandle> QuerySelectorAllHandleAsync(string selector)A utility function to be used with Object%5b%5d).
Parameters
| Name | Type | Description |
|---|---|---|
selector |
string | A selector to query page for. |
Returns: Task<IJSHandle> — Task which resolves to a IJSHandle of document.querySelectorAll result.
QuerySelectorAsync(string)
Section titled “QuerySelectorAsync(string)”public Task<IElementHandle> QuerySelectorAsync(string selector)The method runs document.querySelector within the page. If no element matches the selector, the return value resolve to null.
Parameters
| Name | Type | Description |
|---|---|---|
selector |
string | A selector to query page for. |
Returns: Task<IElementHandle> — Task which resolves to IElementHandle pointing to the frame element.
Shortcut for page.MainFrame.QuerySelectorAsync(selector).
RecordAsync(RecordOptions)
Section titled “RecordAsync(RecordOptions)”[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The caller is responsible for disposing the returned recording.")]public Task<ScreenRecording> RecordAsync(RecordOptions options = null)Records this IPage using the Chrome DevTools Protocol <a href=“https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-startScreenRecording">Page.startScreenRecording</a> API.
Parameters
| Name | Type | Description |
|---|---|---|
options |
RecordOptions | Recording options. |
Returns: Task<ScreenRecording> — A task which resolves to a ScreenRecording that can be used to stop the recording.
Outputs mp4 video stream.
ReloadAsync(ReloadOptions)
Section titled “ReloadAsync(ReloadOptions)”public abstract Task<IResponse> ReloadAsync(ReloadOptions options)Reloads the page.
Parameters
| Name | Type | Description |
|---|---|---|
options |
ReloadOptions | Navigation options. |
Returns: Task<IResponse> — Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
ReloadAsync(int?, WaitUntilNavigation[])
Section titled “ReloadAsync(int?, WaitUntilNavigation[])”public Task<IResponse> ReloadAsync(int? timeout = null, WaitUntilNavigation[] waitUntil = null)Reloads the page.
Parameters
| Name | Type | Description |
|---|---|---|
timeout |
int? | Maximum navigation time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. |
waitUntil |
WaitUntilNavigation\[\] |
When to consider navigation succeeded, defaults to Load. Given an array of WaitUntilNavigation, navigation is considered to be successful after all events have been fired. |
Returns: Task<IResponse> — Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
RemoveExposedFunctionAsync(string)
Section titled “RemoveExposedFunctionAsync(string)”public abstract Task RemoveExposedFunctionAsync(string name)Removes a previously added function via Action).
Parameters
| Name | Type | Description |
|---|---|---|
name |
string | Name of the function to remove. |
Returns: Task — Task.
RemoveRequestInterceptor(Func<IRequest, Task>)
Section titled “RemoveRequestInterceptor(Func<IRequest, Task>)”public void RemoveRequestInterceptor(Func<IRequest, Task> interceptionTask)Removes a previously added request interceptor.
Parameters
| Name | Type | Description |
|---|---|---|
interceptionTask |
Func<IRequest, Task> | Interception task. |
RemoveScriptToEvaluateOnNewDocumentAsync(string)
Section titled “RemoveScriptToEvaluateOnNewDocumentAsync(string)”public abstract Task RemoveScriptToEvaluateOnNewDocumentAsync(string identifier)Removes script that injected into page by EvaluateExpressionOnNewDocumentAsync(string) or EvaluateExpressionOnNewDocumentAsync(string).
Parameters
| Name | Type | Description |
|---|---|---|
identifier |
string | Function identifier. |
Returns: Task — A task that resolves when the script is removed.
ResizeAsync(int, int)
Section titled “ResizeAsync(int, int)”public abstract Task ResizeAsync(int contentWidth, int contentHeight)Resizes the browser window of this page so that the content area (excluding browser UI) has the specified width and height.
Parameters
| Name | Type | Description |
|---|---|---|
contentWidth |
int | The desired width of the content area in pixels. |
contentHeight |
int | The desired height of the content area in pixels. |
Returns: Task — A task that resolves when the resize operation is complete.
This is an experimental API.
ScreencastAsync(ScreencastOptions)
Section titled “ScreencastAsync(ScreencastOptions)”[Obsolete("Use RecordAsync instead.")][SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The caller is responsible for disposing the returned recorder.")]public Task<ScreenRecorder> ScreencastAsync(ScreencastOptions options = null)Captures a screencast of this IPage.
Parameters
| Name | Type | Description |
|---|---|---|
options |
ScreencastOptions | Screencast options. |
Returns: Task<ScreenRecorder> — A Task which resolves to a ScreenRecorder that can be used to stop the recording.
By default, all recordings will be WebM format using the VP9 video codec, with a frame rate of 30 FPS. You must have ffmpeg installed on your system.
ScreenshotAsync(string)
Section titled “ScreenshotAsync(string)”public Task ScreenshotAsync(string file)Captures a screenshot of this IPage.
Parameters
| Name | Type | Description |
|---|---|---|
file |
string | The file path to save the image to. The screenshot type will be inferred from file extension. If path is a relative path, then it is resolved relative to current working directory. If no path is provided, the image won’t be saved to the disk. |
Returns: Task — The screenshot task.
ScreenshotAsync(string, ScreenshotOptions)
Section titled “ScreenshotAsync(string, ScreenshotOptions)”public Task ScreenshotAsync(string file, ScreenshotOptions options)Takes a screenshot of the page.
Parameters
| Name | Type | Description |
|---|---|---|
file |
string | The file path to save the image to. The screenshot type will be inferred from file extension. If path is a relative path, then it is resolved relative to current working directory. If no path is provided, the image won’t be saved to the disk. |
options |
ScreenshotOptions | Screenshot options. |
Returns: Task — The screenshot task.
ScreenshotBase64Async()
Section titled “ScreenshotBase64Async()”public Task<string> ScreenshotBase64Async()Takes a screenshot of the page.
Returns: Task<string> — Task which resolves to a string containing the image data as base64.
ScreenshotBase64Async(ScreenshotOptions)
Section titled “ScreenshotBase64Async(ScreenshotOptions)”public Task<string> ScreenshotBase64Async(ScreenshotOptions options)Takes a screenshot of the page.
Parameters
| Name | Type | Description |
|---|---|---|
options |
ScreenshotOptions | Screenshot options. |
Returns: Task<string> — Task which resolves to a string containing the image data as base64.
ScreenshotDataAsync()
Section titled “ScreenshotDataAsync()”public Task<byte[]> ScreenshotDataAsync()Takes a screenshot of the page.
Returns: Task<byte[]> — Task which resolves to a byte[] containing the image data.
ScreenshotDataAsync(ScreenshotOptions)
Section titled “ScreenshotDataAsync(ScreenshotOptions)”public Task<byte[]> ScreenshotDataAsync(ScreenshotOptions options)Takes a screenshot of the page.
Parameters
| Name | Type | Description |
|---|---|---|
options |
ScreenshotOptions | Screenshot options. |
Returns: Task<byte[]> — Task which resolves to a byte[] containing the image data.
ScreenshotStreamAsync()
Section titled “ScreenshotStreamAsync()”public Task<Stream> ScreenshotStreamAsync()Takes a screenshot of the page.
Returns: Task<Stream> — Task which resolves to a Stream containing the image data.
ScreenshotStreamAsync(ScreenshotOptions)
Section titled “ScreenshotStreamAsync(ScreenshotOptions)”public Task<Stream> ScreenshotStreamAsync(ScreenshotOptions options)Takes a screenshot of the page.
Parameters
| Name | Type | Description |
|---|---|---|
options |
ScreenshotOptions | Screenshot options. |
Returns: Task<Stream> — Task which resolves to a Stream containing the image data.
SelectAsync(string, params string[])
Section titled “SelectAsync(string, params string[])”public Task<string[]> SelectAsync(string selector, params string[] values)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.
Parameters
| Name | Type | Description |
|---|---|---|
selector |
string | A selector to query page for. |
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. |
Returns: Task<string[]> — Returns an array of option values that have been successfully selected.
Exceptions
| Type | Condition |
|---|---|
| SelectorException | If there’s no element matching <code class=“paramref”>selector</code>. |
SetBurstModeOffAsync()
Section titled “SetBurstModeOffAsync()”public abstract Task SetBurstModeOffAsync()Resets the background color and Viewport after taking Screenshots using BurstMode.
Returns: Task — The burst mode off.
SetBypassCSPAsync(bool)
Section titled “SetBypassCSPAsync(bool)”public abstract Task SetBypassCSPAsync(bool enabled)Toggles bypassing page’s Content-Security-Policy.
Parameters
| Name | Type | Description |
|---|---|---|
enabled |
bool | sets bypassing of page’s Content-Security-Policy. |
Returns: Task — A Task which resolves after the message is sent to the browser.
CSP bypassing happens at the moment of CSP initialization rather then evaluation. Usually this means that SetBypassCSPAsync(bool) should be called before navigating to the domain.
SetBypassServiceWorkerAsync(bool)
Section titled “SetBypassServiceWorkerAsync(bool)”public abstract Task SetBypassServiceWorkerAsync(bool bypass)Toggles ignoring of service worker for each request.
Parameters
| Name | Type | Description |
|---|---|---|
bypass |
bool | When true bypasses service worker. |
Returns: Task — A task that resolves when the message is sent to the browser.
SetCacheEnabledAsync(bool)
Section titled “SetCacheEnabledAsync(bool)”public abstract Task SetCacheEnabledAsync(bool enabled = true)Toggles ignoring cache for each request based on the enabled state. By default, caching is enabled.
Parameters
| Name | Type | Description |
|---|---|---|
enabled |
bool | sets the enabled state of the cache. |
Returns: Task — Task.
SetContentAsync(string, NavigationOptions)
Section titled “SetContentAsync(string, NavigationOptions)”[Obsolete("Use SetContentAsync(string, SetContentOptions) instead. The networkidle0 and networkidle2 wait conditions never worked reliably with SetContent.")]public Task SetContentAsync(string html, NavigationOptions options)Sets the HTML markup to the page.
Parameters
| Name | Type | Description |
|---|---|---|
html |
string | HTML markup to assign to the page. |
options |
NavigationOptions | The navigations options. |
Returns: Task — Task.
SetContentAsync(string, SetContentOptions)
Section titled “SetContentAsync(string, SetContentOptions)”public Task SetContentAsync(string html, SetContentOptions options = null)Sets the HTML markup to the page.
Parameters
| Name | Type | Description |
|---|---|---|
html |
string | HTML markup to assign to the page. |
options |
SetContentOptions | The options. The Networkidle0 and Networkidle2 wait conditions are not supported for SetContent. |
Returns: Task — Task.
SetCookieAsync(params CookieParam[])
Section titled “SetCookieAsync(params CookieParam[])”public abstract Task SetCookieAsync(params CookieParam[] cookies)Clears all of the current cookies and then sets the cookies for the page.
Parameters
| Name | Type | Description |
|---|---|---|
cookies |
CookieParam\[\] |
Cookies to set. |
Returns: Task — Task.
SetDragInterceptionAsync(bool)
Section titled “SetDragInterceptionAsync(bool)”public abstract Task SetDragInterceptionAsync(bool enabled)Whether to enable drag interception.
Parameters
| Name | Type | Description |
|---|---|---|
enabled |
bool | Interception enabled. |
Returns: Task — A Task that resolves when the message was confirmed by the browser.
Activating drag interception enables the Input.drag,
methods This provides the capability to capture drag events emitted
on the page, which can then be used to simulate drag-and-drop.
SetExtraHttpHeadersAsync(Dictionary<string, string>)
Section titled “SetExtraHttpHeadersAsync(Dictionary<string, string>)”public abstract Task SetExtraHttpHeadersAsync(Dictionary<string, string> headers)Sets extra HTTP headers that will be sent with every request the page initiates.
Parameters
| Name | Type | Description |
|---|---|---|
headers |
Dictionary<string, string> | Additional http headers to be sent with every request. |
Returns: Task — Task.
SetGeolocationAsync(GeolocationOption)
Section titled “SetGeolocationAsync(GeolocationOption)”public abstract Task SetGeolocationAsync(GeolocationOption options)Sets the page’s geolocation.
Parameters
| Name | Type | Description |
|---|---|---|
options |
GeolocationOption | Geolocation options. Pass null to remove the geolocation override. |
Returns: Task — The task.
Consider using OverridePermission%7d) to grant permissions for the page to read its geolocation.
SetJavaScriptEnabledAsync(bool)
Section titled “SetJavaScriptEnabledAsync(bool)”public abstract Task SetJavaScriptEnabledAsync(bool enabled)Enables/Disables Javascript on the page.
Parameters
| Name | Type | Description |
|---|---|---|
enabled |
bool | Whether or not to enable JavaScript on the page. |
Returns: Task — Task.
SetOfflineModeAsync(bool)
Section titled “SetOfflineModeAsync(bool)”public abstract Task SetOfflineModeAsync(bool value)Set offline mode for the page.
Parameters
| Name | Type | Description |
|---|---|---|
value |
bool | When true enables offline mode for the page. |
Returns: Task — Result task.
SetRequestInterceptionAsync(bool)
Section titled “SetRequestInterceptionAsync(bool)”public abstract Task SetRequestInterceptionAsync(bool value)Activating request interception enables AbortAsync,
ContinueAsync and RespondAsync methods.
Parameters
| Name | Type | Description |
|---|---|---|
value |
bool | Whether to enable request interception.. |
Returns: Task — The request interception task.
SetUserAgentAsync(SetUserAgentOptions)
Section titled “SetUserAgentAsync(SetUserAgentOptions)”public abstract Task SetUserAgentAsync(SetUserAgentOptions options)Sets the user agent, user agent metadata, and platform.
Parameters
| Name | Type | Description |
|---|---|---|
options |
SetUserAgentOptions | User agent options. |
Returns: Task — Task.
SetUserAgentAsync(string, UserAgentMetadata)
Section titled “SetUserAgentAsync(string, UserAgentMetadata)”public abstract Task SetUserAgentAsync(string userAgent, UserAgentMetadata userAgentData = null)Sets the user agent to be used in this page.
Parameters
| Name | Type | Description |
|---|---|---|
userAgent |
string | Specific user agent to use in this page. |
userAgentData |
UserAgentMetadata | Specific user agent client hint data to use in this page. |
Returns: Task — Task.
SetViewportAsync(ViewPortOptions)
Section titled “SetViewportAsync(ViewPortOptions)”public abstract Task SetViewportAsync(ViewPortOptions viewport)Sets the viewport. In the case of multiple pages in a single browser, each page can have its own viewport size. SetViewportAsync(ViewPortOptions) 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.
Parameters
| Name | Type | Description |
|---|---|---|
viewport |
ViewPortOptions | Viewport options. |
Returns: Task — The viewport task.
Example
using(var page = await browser.NewPageAsync()) { await page.SetViewPortAsync(new ViewPortOptions { Width = 640, Height = 480, DeviceScaleFactor = 1 }); await page.goto(‘https://www.example.com’); }
TabInfoAsync()
Section titled “TabInfoAsync()”public abstract Task<TabInfo> TabInfoAsync()Returns information about the browser tab of this page. The result is a snapshot and is not updated when the tab changes.
Returns: Task<TabInfo> — A task that resolves to the tab info, or null if the page is not in a tab strip (for example, in chrome-headless-shell) or the browser does not report tab information.
This is an experimental API.
TapAsync(string)
Section titled “TapAsync(string)”public Task TapAsync(string selector)Fetches an element with <code class=“paramref”>selector</code>, scrolls it into view if needed, and then uses Touchscreen to tap in the center of the element.
Parameters
| Name | Type | Description |
|---|---|---|
selector |
string | A selector to search for element to tap. If there are multiple elements satisfying the selector, the first will be clicked. |
Returns: Task — Task which resolves when the element matching <code class=“paramref”>selector</code> is successfully tapped.
Exceptions
| Type | Condition |
|---|---|
| SelectorException | If there’s no element matching <code class=“paramref”>selector</code>. |
TriggerExtensionActionAsync(Extension)
Section titled “TriggerExtensionActionAsync(Extension)”public abstract Task TriggerExtensionActionAsync(Extension extension)Triggers an extension action for the given extension.
Parameters
| Name | Type | Description |
|---|---|---|
extension |
Extension | The extension to trigger the action for. |
Returns: Task — A task that completes when the extension action has been triggered.
TypeAsync(string, string, TypeOptions)
Section titled “TypeAsync(string, string, TypeOptions)”public Task TypeAsync(string selector, string text, TypeOptions options = null)Sends a keydown, keypress/input, and keyup event for each character in the text.
Parameters
| Name | Type | Description |
|---|---|---|
selector |
string | A selector of an element to type into. If there are multiple elements satisfying the selector, the first will be used. |
text |
string | A text to type into a focused element. |
options |
TypeOptions | The options to apply to the type operation. |
Returns: Task — Task.
Exceptions
| Type | Condition |
|---|---|
| SelectorException | If there’s no element matching <code class=“paramref”>selector</code>. |
To press a special key, like Control or ArrowDown use PressOptions).
Example
await page.TypeAsync("#mytextarea", "Hello"); // Types instantlyawait page.TypeAsync("#mytextarea", "World", new TypeOptions { Delay = 100 }); // Types slower, like a userWaitForDevicePromptAsync(WaitForOptions)
Section titled “WaitForDevicePromptAsync(WaitForOptions)”public Task<DeviceRequestPrompt> WaitForDevicePromptAsync(WaitForOptions options = null)This 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.
Parameters
| Name | Type | Description |
|---|---|---|
options |
WaitForOptions | Optional waiting parameters. |
Returns: Task<DeviceRequestPrompt> — A task that resolves after the page gets the prompt.
Example
WaitForExpressionAsync(string, WaitForFunctionOptions)
Section titled “WaitForExpressionAsync(string, WaitForFunctionOptions)”public Task<IJSHandle> WaitForExpressionAsync(string script, WaitForFunctionOptions options = null)Waits for an expression to be evaluated to a truthy value.
Parameters
| Name | Type | Description |
|---|---|---|
script |
string | Expression to be evaluated in browser context. |
options |
WaitForFunctionOptions | Optional waiting parameters. |
Returns: Task<IJSHandle> — A task that resolves when the script returns a truthy value.
WaitForFileChooserAsync(WaitForOptions)
Section titled “WaitForFileChooserAsync(WaitForOptions)”public abstract Task<FileChooser> WaitForFileChooserAsync(WaitForOptions options = null)Waits for a page to open a file picker.
Parameters
| Name | Type | Description |
|---|---|---|
options |
WaitForOptions | Optional waiting parameters. |
Returns: Task<FileChooser> — A task that resolves after a page requests a file picker.
In non-headless Chromium, this method results in the native file picker dialog not showing up for the user.
Example
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.
var waitTask = page.WaitForFileChooserAsync();await Task.WhenAll( waitTask, page.ClickAsync("#upload-file-button")); // some button that triggers file selection
await waitTask.Result.AcceptAsync('/tmp/myfile.pdf');This must be called before the file chooser is launched. It will not return a currently active file chooser.
WaitForFrameAsync(Func<IFrame, bool>, WaitForOptions)
Section titled “WaitForFrameAsync(Func<IFrame, bool>, WaitForOptions)”public Task<IFrame> WaitForFrameAsync(Func<IFrame, bool> predicate, WaitForOptions options = null)Waits for a frame.
Parameters
| Name | Type | Description |
|---|---|---|
predicate |
Func<IFrame, bool> | Function which looks for a matching frame. |
options |
WaitForOptions | Options. |
Returns: Task<IFrame> — A task which resolves when a matching frame was attached to the page.
Example
var frame = await page.WaitForFrameAsync(frame => frame.Name == "Test");WaitForFrameAsync(string, WaitForOptions)
Section titled “WaitForFrameAsync(string, WaitForOptions)”public Task<IFrame> WaitForFrameAsync(string url, WaitForOptions options = null)Waits for a frame.
Parameters
| Name | Type | Description |
|---|---|---|
url |
string | Frame url. |
options |
WaitForOptions | Options. |
Returns: Task<IFrame> — A task which resolves when a matching frame was attached to the page.
Example
var frame = await page.WaitForFrameAsync(frame => frame.Name == "Test");WaitForFunctionAsync(string, WaitForFunctionOptions, params object[])
Section titled “WaitForFunctionAsync(string, WaitForFunctionOptions, params object[])”public Task<IJSHandle> WaitForFunctionAsync(string script, WaitForFunctionOptions options = null, params object[] args)Waits for a function to be evaluated to a truthy value.
Parameters
| Name | Type | Description |
|---|---|---|
script |
string | Function to be evaluated in browser context. |
options |
WaitForFunctionOptions | Optional waiting parameters. |
args |
object[] | Arguments to pass to script. |
Returns: Task<IJSHandle> — A task that resolves when the script returns a truthy value.
WaitForFunctionAsync(string, params object[])
Section titled “WaitForFunctionAsync(string, params object[])”public Task<IJSHandle> WaitForFunctionAsync(string script, params object[] args)Waits for a function to be evaluated to a truthy value.
Parameters
| Name | Type | Description |
|---|---|---|
script |
string | Function to be evaluated in browser context. |
args |
object[] | Arguments to pass to script. |
Returns: Task<IJSHandle> — A task that resolves when the script returns a truthy value.
WaitForNavigationAsync(NavigationOptions)
Section titled “WaitForNavigationAsync(NavigationOptions)”public Task<IResponse> WaitForNavigationAsync(NavigationOptions options = null)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.
Parameters
| Name | Type | Description |
|---|---|---|
options |
NavigationOptions | navigation options. |
Returns: Task<IResponse> — Task which resolves to the main resource response.
In case of multiple redirects, the navigation will resolve with the response of the last redirect.
In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with null.
Usage of the History API <a href=“https://developer.mozilla.org/en-US/docs/Web/API/History_API">https://developer.mozilla.org/en-US/docs/Web/API/History_API</a> to change the URL is considered a navigation.
Example
var navigationTask = page.WaitForNavigationAsync();await page.ClickAsync("a.my-link");await navigationTask;WaitForNetworkIdleAsync(WaitForNetworkIdleOptions)
Section titled “WaitForNetworkIdleAsync(WaitForNetworkIdleOptions)”public Task WaitForNetworkIdleAsync(WaitForNetworkIdleOptions options = null)Waits for Network Idle.
Parameters
| Name | Type | Description |
|---|---|---|
options |
WaitForNetworkIdleOptions | Optional waiting parameters. |
Returns: Task — returns Task which resolves when network is idle.
Example
page.EvaluateFunctionAsync("() => fetch('some-url')");await page.WaitForNetworkIdle(); // The Task resolves after fetch above finishesWaitForRequestAsync(Func<IRequest, bool>, WaitForOptions)
Section titled “WaitForRequestAsync(Func<IRequest, bool>, WaitForOptions)”public Task<IRequest> WaitForRequestAsync(Func<IRequest, bool> predicate, WaitForOptions options = null)Waits for a request.
Parameters
| Name | Type | Description |
|---|---|---|
predicate |
Func<IRequest, bool> | Function which looks for a matching request. |
options |
WaitForOptions | Options. |
Returns: Task<IRequest> — A task which resolves when a matching request was made.
Example
var request = await page.WaitForRequestAsync(request => request.Url === "http://example.com" && request.Method === HttpMethod.Get;return request.Url;WaitForRequestAsync(string, WaitForOptions)
Section titled “WaitForRequestAsync(string, WaitForOptions)”public Task<IRequest> WaitForRequestAsync(string url, WaitForOptions options = null)Waits for a request.
Parameters
| Name | Type | Description |
|---|---|---|
url |
string | URL to wait for. |
options |
WaitForOptions | Options. |
Returns: Task<IRequest> — A task which resolves when a matching request was made.
Example
var firstRequest = await page.WaitForRequestAsync("http://example.com/resource");return firstRequest.Url;WaitForResponseAsync(Func<IResponse, bool>, WaitForOptions)
Section titled “WaitForResponseAsync(Func<IResponse, bool>, WaitForOptions)”public Task<IResponse> WaitForResponseAsync(Func<IResponse, bool> predicate, WaitForOptions options = null)Waits for a response.
Parameters
| Name | Type | Description |
|---|---|---|
predicate |
Func<IResponse, bool> | Function which looks for a matching response. |
options |
WaitForOptions | Options. |
Returns: Task<IResponse> — A task which resolves when a matching response is received.
Example
var response = await page.WaitForResponseAsync(response => response.Url === "http://example.com" && response.Status === HttpStatus.Ok;return response.Url;WaitForResponseAsync(Func<IResponse, Task<bool>>, WaitForOptions)
Section titled “WaitForResponseAsync(Func<IResponse, Task<bool>>, WaitForOptions)”public Task<IResponse> WaitForResponseAsync(Func<IResponse, Task<bool>> predicate, WaitForOptions options = null)Waits for a response.
Parameters
| Name | Type | Description |
|---|---|---|
predicate |
Func<IResponse, Task<bool>> | Function which looks for a matching response. |
options |
WaitForOptions | Options. |
Returns: Task<IResponse> — A task which resolves when a matching response is received.
Example
var response = await page.WaitForResponseAsync(response => response.Url === "http://example.com" && response.Status === HttpStatus.Ok;return response.Url;WaitForResponseAsync(string, WaitForOptions)
Section titled “WaitForResponseAsync(string, WaitForOptions)”public Task<IResponse> WaitForResponseAsync(string url, WaitForOptions options = null)Waits for a response.
Parameters
| Name | Type | Description |
|---|---|---|
url |
string | URL to wait for. |
options |
WaitForOptions | Options. |
Returns: Task<IResponse> — A task which resolves when a matching response is received.
Example
var firstResponse = await page.WaitForResponseAsync("http://example.com/resource");return firstResponse.Url;WaitForSelectorAsync(string, WaitForSelectorOptions)
Section titled “WaitForSelectorAsync(string, WaitForSelectorOptions)”public Task<IElementHandle> WaitForSelectorAsync(string selector, WaitForSelectorOptions options = null)Waits for a selector to be added to the DOM.
Parameters
| Name | Type | Description |
|---|---|---|
selector |
string | A selector of an element to wait for. |
options |
WaitForSelectorOptions | Optional waiting parameters. |
Returns: Task<IElementHandle> — A task that 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.
WaitForXPathAsync(string, WaitForSelectorOptions)
Section titled “WaitForXPathAsync(string, WaitForSelectorOptions)”public Task<IElementHandle> WaitForXPathAsync(string xpath, WaitForSelectorOptions options = null)Waits for a xpath selector to be added to the DOM.
Parameters
| Name | Type | Description |
|---|---|---|
xpath |
string | A xpath selector of an element to wait for. |
options |
WaitForSelectorOptions | Optional waiting parameters. |
Returns: Task<IElementHandle> — A task which resolves when element specified by xpath string is added to DOM.
Resolves to null if waiting for hidden: true and xpath is not found in DOM.
Example
var browser = await Puppeteer.LaunchAsync(new LaunchOptions());var page = await browser.NewPageAsync();string currentURL = null;page .WaitForXPathAsync("//img") .ContinueWith(_ => Console.WriteLine("First URL with image: " + currentURL));foreach (var current in new[] { "https://example.com", "https://google.com", "https://bbc.com" }){ currentURL = current; await page.GoToAsync(currentURL);}await browser.CloseAsync();WindowIdAsync()
Section titled “WindowIdAsync()”public abstract Task<string> WindowIdAsync()Returns the page’s window ID.
Returns: Task<string> — A task that resolves to the window ID string.
This is an experimental API.
XPathAsync(string)
Section titled “XPathAsync(string)”public Task<IElementHandle[]> XPathAsync(string expression)Evaluates the XPath expression.
Parameters
| Name | Type | Description |
|---|---|---|
expression |
string | Expression to evaluate <a href=“https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate">https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate</a>. |
Returns: Task<IElementHandle[]> — Task which resolves to an array of IElementHandle.
Shortcut for page.MainFrame.XPathAsync(expression).
Made with love by Dario Kondratiuk