Table of Contents

Class CdpPage

Namespace
PuppeteerSharp.Cdp
Assembly
PuppeteerSharp.dll

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.

public class CdpPage : Page, IPage, IDisposable, IAsyncDisposable
Inheritance
CdpPage
Implements

Properties

Browser

Browser.

protected override Browser Browser { get; }

Property Value

Browser

BrowserContext

Get the browser context that the page belongs to.

public override IBrowserContext BrowserContext { get; }

Property Value

IBrowserContext

Client

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.

public override CDPSession Client { get; }

Property Value

CDPSession

Frames

Gets all frames attached to the page.

public override IFrame[] Frames { get; }

Property Value

IFrame[]

An array of all frames attached to the page.

IsJavaScriptEnabled

If the page has JavaScript enabled.

public override bool IsJavaScriptEnabled { get; }

Property Value

bool

MainFrame

Gets page's main frame.

public override IFrame MainFrame { get; }

Property Value

IFrame

Remarks

Page is guaranteed to have a main frame which persists during navigations.

Target

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.

public override Target Target { get; }

Property Value

Target

Workers

Gets all workers in the page.

public override WebWorker[] Workers { get; }

Property Value

WebWorker[]

Methods

AuthenticateAsync(Credentials)

Provide credentials for http authentication https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication.

public override Task AuthenticateAsync(Credentials credentials)

Parameters

credentials Credentials

The credentials.

Returns

Task

A Task which resolves after the message is sent to the browser.

Remarks

To disable authentication, pass null.

BringToFrontAsync()

Brings page to front (activates tab).

public override Task BringToFrontAsync()

Returns

Task

A task that resolves when the message has been sent to Chromium.

CloseAsync(PageCloseOptions)

Closes the page.

public override Task CloseAsync(PageCloseOptions options = null)

Parameters

options PageCloseOptions

Close options.

Returns

Task

Task.

DeleteCookieAsync(params CookieParam[])

Deletes cookies from the page.

public override Task DeleteCookieAsync(params CookieParam[] cookies)

Parameters

cookies CookieParam[]

Cookies to delete.

Returns

Task

Task.

EmulateCPUThrottlingAsync(decimal?)

Enables CPU throttling to emulate slow CPUs.

public override Task EmulateCPUThrottlingAsync(decimal? factor = null)

Parameters

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.

EmulateIdleStateAsync(EmulateIdleOverrides)

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

public override Task EmulateIdleStateAsync(EmulateIdleOverrides overrides = null)

Parameters

overrides EmulateIdleOverrides

Returns

Task

A task that resolves when the message has been sent to the browser.

Examples

// set idle emulation
await page.EmulateIdleStateAsync(new EmulateIdleOverrides() {IsUserActive = true, IsScreenUnlocked = false});
// do some checks here
...
// clear idle emulation
await page.EmulateIdleStateAsync();

EmulateMediaFeaturesAsync(IEnumerable<MediaFeatureValue>)

Given an array of media feature objects, emulates CSS media features on the page.

public override Task EmulateMediaFeaturesAsync(IEnumerable<MediaFeatureValue> features)

Parameters

features IEnumerable<MediaFeatureValue>

Features to apply.

Returns

Task

Emulate features task.

Examples

await page.EmulateMediaFeaturesAsync(new MediaFeature[]{ new MediaFeature { MediaFeature =  MediaFeature.PrefersColorScheme, Value = "dark" }});
await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: dark)').matches)");
// → true
await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: light)').matches)");
// → false
await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");
// → false
await page.EmulateMediaFeaturesAsync(new MediaFeature[]{ new MediaFeature { MediaFeature = MediaFeature.PrefersReducedMotion, Value = "reduce" }});
await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-reduced-motion: reduce)').matches)");
// → true
await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");
// → false
await 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)");
// → true
await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: light)').matches)");
// → false
await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");
// → false
await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-reduced-motion: reduce)').matches)");
// → true
await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");
// → false

EmulateMediaTypeAsync(MediaType)

Emulates a media such as screen or print.

public override Task EmulateMediaTypeAsync(MediaType type)

Parameters

type MediaType

Media to set.

Returns

Task

Emulate media type task.

Examples

await page.EvaluateFunctionAsync<bool>("() => matchMedia('screen').matches)");
// → true
await page.EvaluateFunctionAsync<bool>("() => matchMedia('print').matches)");
// → true
await page.EmulateMediaTypeAsync(MediaType.Print);
await page.EvaluateFunctionAsync<bool>("() => matchMedia('screen').matches)");
// → false
await page.EvaluateFunctionAsync<bool>("() => matchMedia('print').matches)");
// → true
await page.EmulateMediaTypeAsync(MediaType.None);
await page.EvaluateFunctionAsync<bool>("() => matchMedia('screen').matches)");
// → true
await page.EvaluateFunctionAsync<bool>("() => matchMedia('print').matches)");
// → true

EmulateNetworkConditionsAsync(NetworkConditions)

Emulates network conditions.

public override Task EmulateNetworkConditionsAsync(NetworkConditions networkConditions)

Parameters

networkConditions NetworkConditions

Passing null disables network condition emulation.

Returns

Task

Result task.

Remarks

NOTE This does not affect WebSockets and WebRTC PeerConnections (see https://crbug.com/563644).

EmulateTimezoneAsync(string)

Changes the timezone of the page.

public override Task EmulateTimezoneAsync(string timezoneId)

Parameters

timezoneId string

Timezone to set. See ICU’s metaZones.txt for a list of supported timezone IDs. Passing null disables timezone emulation.

Returns

Task

The viewport task.

EmulateVisionDeficiencyAsync(VisionDeficiency)

Simulates the given vision deficiency on the page.

public override Task EmulateVisionDeficiencyAsync(VisionDeficiency type)

Parameters

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.

Examples

await Page.EmulateVisionDeficiencyAsync(VisionDeficiency.Achromatopsia); await Page.ScreenshotAsync("Achromatopsia.png").

EvaluateExpressionOnNewDocumentAsync(string)

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.
public override Task<NewDocumentScriptEvaluation> EvaluateExpressionOnNewDocumentAsync(string expression)

Parameters

expression string

Javascript expression to be evaluated in browser context.

Returns

Task<NewDocumentScriptEvaluation>

Task.

Examples

An example of overriding the navigator.languages property before the page loads:

await page.EvaluateExpressionOnNewDocumentAsync("window.__example = true;");

Remarks

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.

EvaluateFunctionOnNewDocumentAsync(string, params object[])

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.
public override Task<NewDocumentScriptEvaluation> EvaluateFunctionOnNewDocumentAsync(string pageFunction, params object[] args)

Parameters

pageFunction string

Function to be evaluated in browser context.

args object[]

Arguments to pass to pageFunction.

Returns

Task<NewDocumentScriptEvaluation>

Task.

Examples

An example of overriding the navigator.languages property before the page loads:

await page.EvaluateFunctionOnNewDocumentAsync("() => window.__example = true");

Remarks

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.

ExposeFunctionAsync(string, Delegate)

Internal add exposed functions.

protected override Task ExposeFunctionAsync(string name, Delegate puppeteerFunction)

Parameters

name string

Function name.

puppeteerFunction Delegate

Puppeteer function.

Returns

Task

A Task that completes when the function has been added.

GetCookiesAsync(params string[])

Returns the page's cookies.

public override Task<CookieParam[]> GetCookiesAsync(params string[] urls)

Parameters

urls string[]

Url's to return cookies for.

Returns

Task<CookieParam[]>

Array of cookies.

Remarks

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.

GoBackAsync(NavigationOptions)

Navigate to the previous page in history.

public override Task<IResponse> GoBackAsync(NavigationOptions options = null)

Parameters

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)

Navigate to the next page in history.

public override Task<IResponse> GoForwardAsync(NavigationOptions options = null)

Parameters

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.

MetricsAsync()

Returns metrics.

public override Task<Dictionary<string, decimal>> MetricsAsync()

Returns

Task<Dictionary<string, decimal>>

Task which resolves into a list of metrics.

Remarks

All timestamps are in monotonic time: monotonically increasing time in seconds since an arbitrary point in the past.

PdfInternalAsync(string, PdfOptions)

PDF implementation.

protected override Task<byte[]> PdfInternalAsync(string file, PdfOptions options)

Parameters

file string

File path.

options PdfOptions

PDF options.

Returns

Task<byte[]>

PDF data.

PerformScreenshotAsync(ScreenshotType, ScreenshotOptions)

Screenshot implementation.

protected override Task<string> PerformScreenshotAsync(ScreenshotType type, ScreenshotOptions options)

Parameters

type ScreenshotType

Screenshot type.

options ScreenshotOptions

Options.

Returns

Task<string>

The screenshot as a base64 string.

QueryObjectsAsync(IJSHandle)

The method iterates JavaScript heap and finds all the objects with the given prototype. Shortcut for page.MainFrame.GetExecutionContextAsync().QueryObjectsAsync(prototypeHandle).

public override Task<IJSHandle> QueryObjectsAsync(IJSHandle prototypeHandle)

Parameters

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.

ReloadAsync(NavigationOptions)

Reloads the page.

public override Task<IResponse> ReloadAsync(NavigationOptions options)

Parameters

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.

See Also

RemoveExposedFunctionAsync(string)

Removes a previously added function via ExposeFunctionAsync(string, Action).

public override Task RemoveExposedFunctionAsync(string name)

Parameters

name string

Name of the function to remove.

Returns

Task

Task.

RemoveScriptToEvaluateOnNewDocumentAsync(string)

public override Task RemoveScriptToEvaluateOnNewDocumentAsync(string identifier)

Parameters

identifier string

Function identifier.

Returns

Task

A task that resolves when the script is removed.

SetBurstModeOffAsync()

Resets the background color and Viewport after taking Screenshots using BurstMode.

public override Task SetBurstModeOffAsync()

Returns

Task

The burst mode off.

SetBypassCSPAsync(bool)

Toggles bypassing page's Content-Security-Policy.

public override Task SetBypassCSPAsync(bool enabled)

Parameters

enabled bool

sets bypassing of page's Content-Security-Policy.

Returns

Task

A Task which resolves after the message is sent to the browser.

Remarks

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)

Toggles ignoring of service worker for each request.

public override Task SetBypassServiceWorkerAsync(bool bypass)

Parameters

bypass bool

When true bypasses service worker.

Returns

Task

A task that resolves when the message is sent to the browser.

SetCacheEnabledAsync(bool)

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

public override Task SetCacheEnabledAsync(bool enabled = true)

Parameters

enabled bool

sets the enabled state of the cache.

Returns

Task

Task.

SetCookieAsync(params CookieParam[])

Clears all of the current cookies and then sets the cookies for the page.

public override Task SetCookieAsync(params CookieParam[] cookies)

Parameters

cookies CookieParam[]

Cookies to set.

Returns

Task

Task.

SetDragInterceptionAsync(bool)

Whether to enable drag interception.

public override Task SetDragInterceptionAsync(bool enabled)

Parameters

enabled bool

Interception enabled.

Returns

Task

A Task that resolves when the message was confirmed by the browser.

Remarks

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>)

Sets extra HTTP headers that will be sent with every request the page initiates.

public override Task SetExtraHttpHeadersAsync(Dictionary<string, string> headers)

Parameters

headers Dictionary<string, string>

Additional http headers to be sent with every request.

Returns

Task

Task.

SetGeolocationAsync(GeolocationOption)

Sets the page's geolocation.

public override Task SetGeolocationAsync(GeolocationOption options)

Parameters

options GeolocationOption

Geolocation options.

Returns

Task

The task.

Remarks

Consider using OverridePermissionsAsync(string, IEnumerable<OverridePermission>) to grant permissions for the page to read its geolocation.

SetJavaScriptEnabledAsync(bool)

Enables/Disables Javascript on the page.

public override Task SetJavaScriptEnabledAsync(bool enabled)

Parameters

enabled bool

Whether or not to enable JavaScript on the page.

Returns

Task

Task.

SetOfflineModeAsync(bool)

Set offline mode for the page.

public override Task SetOfflineModeAsync(bool value)

Parameters

value bool

When true enables offline mode for the page.

Returns

Task

Result task.

SetRequestInterceptionAsync(bool)

Activating request interception enables request.AbortAsync, request.ContinueAsync and request.RespondAsync methods.

public override Task SetRequestInterceptionAsync(bool value)

Parameters

value bool

Whether to enable request interception..

Returns

Task

The request interception task.

SetUserAgentAsync(string, UserAgentMetadata)

Sets the user agent to be used in this page.

public override Task SetUserAgentAsync(string userAgent, UserAgentMetadata userAgentData = null)

Parameters

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)

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.

public override Task SetViewportAsync(ViewPortOptions viewport)

Parameters

viewport ViewPortOptions

Viewport options.

Returns

Task

The viewport task.

Examples

using(var page = await browser.NewPageAsync()) { await page.SetViewPortAsync(new ViewPortOptions { Width = 640, Height = 480, DeviceScaleFactor = 1 }); await page.goto('https://www.example.com'); }

WaitForFileChooserAsync(WaitForOptions)

Waits for a page to open a file picker.

public override Task<FileChooser> WaitForFileChooserAsync(WaitForOptions options = null)

Parameters

options WaitForOptions

Optional waiting parameters.

Returns

Task<FileChooser>

A task that resolves after a page requests a file picker.

Examples

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.

Remarks

In non-headless Chromium, this method results in the native file picker dialog not showing up for the user.

WaitForFrameAsync(Func<IFrame, bool>, WaitForOptions)

Waits for a frame.

public override Task<IFrame> WaitForFrameAsync(Func<IFrame, bool> predicate, WaitForOptions options = null)

Parameters

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.

Examples

var frame = await page.WaitForFrameAsync(frame => frame.Name == "Test");

WaitForNetworkIdleAsync(WaitForNetworkIdleOptions)

Waits for Network Idle.

public override Task WaitForNetworkIdleAsync(WaitForNetworkIdleOptions options = null)

Parameters

options WaitForNetworkIdleOptions

Optional waiting parameters.

Returns

Task

returns Task which resolves when network is idle.

Examples

page.EvaluateFunctionAsync("() => fetch('some-url')");
await page.WaitForNetworkIdle(); // The Task resolves after fetch above finishes

WaitForRequestAsync(Func<IRequest, bool>, WaitForOptions)

Waits for a request.

public override Task<IRequest> WaitForRequestAsync(Func<IRequest, bool> predicate, WaitForOptions options = null)

Parameters

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.

Examples

var request = await page.WaitForRequestAsync(request => request.Url === "http://example.com" && request.Method === HttpMethod.Get;
return request.Url;

WaitForResponseAsync(Func<IResponse, Task<bool>>, WaitForOptions)

Waits for a response.

public override Task<IResponse> WaitForResponseAsync(Func<IResponse, Task<bool>> predicate, WaitForOptions options = null)

Parameters

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.

Examples

var response = await page.WaitForResponseAsync(response => response.Url === "http://example.com" && response.Status === HttpStatus.Ok;
return response.Url;