Skip to content

CdpPage

Namespace: PuppeteerSharp.Cdp

public class CdpPage : Page, IPage, IDisposable, IAsyncDisposable

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.

Inheritance: object → Page

Implements: IPage, IDisposable, IAsyncDisposable

View source

protected override Browser Browser { get; }

Browser.

Value: Browser

View source

public override IBrowserContext BrowserContext { get; }

Get the browser context that the page belongs to.

Value: IBrowserContext

View source

public override 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

View source

public override IFrame[] Frames { get; }

Gets all frames attached to the page.

Value: IFrame\[\] — An array of all frames attached to the page.

View source

public override bool IsJavaScriptEnabled { get; }

If the page has JavaScript enabled.

Value: bool

View source

public override IFrame MainFrame { get; }

Gets page’s main frame.

Value: IFrame

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

View source

public override 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

View source

public override 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.

View source

public override WebWorker[] Workers { get; }

Gets all workers in the page.

Value: WebWorker\[\]

View source

public override Task AuthenticateAsync(Credentials credentials)

Provide credentials for http authentication <a href=“https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication"&gt;https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication&lt;/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.

View source

public override Task BringToFrontAsync()

Brings page to front (activates tab).

Returns: Task — A task that resolves when the message has been sent to Chromium.

View source

CaptureHeapSnapshotAsync(HeapSnapshotOptions)

Section titled “CaptureHeapSnapshotAsync(HeapSnapshotOptions)”
public override 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.

View source

public override Task CloseAsync(PageCloseOptions options = null)

Closes the page.

Parameters

Name Type Description
options PageCloseOptions Close options.

Returns: Task — Task.

View source

protected override 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.

View source

public override Task DeleteCookieAsync(params CookieParam[] cookies)

Deletes cookies from the page.

Parameters

Name Type Description
cookies CookieParam\[\] Cookies to delete.

Returns: Task — Task.

View source

public override 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.

View source

public override 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.

View source

EmulateIdleStateAsync(EmulateIdleOverrides)

Section titled “EmulateIdleStateAsync(EmulateIdleOverrides)”
public override Task EmulateIdleStateAsync(EmulateIdleOverrides overrides = null)

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

Parameters

Name Type Description
overrides EmulateIdleOverrides

Returns: Task — A task that resolves when the message has been sent to the browser.

Example

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

View source

public override 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.

View source

EmulateMediaFeaturesAsync(IEnumerable<MediaFeatureValue>)

Section titled “EmulateMediaFeaturesAsync(IEnumerable<MediaFeatureValue>)”
public override 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)");
// → 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

View source

public override 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)");
// → 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

View source

EmulateNetworkConditionsAsync(NetworkConditions)

Section titled “EmulateNetworkConditionsAsync(NetworkConditions)”
public override 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).

View source

public override 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"&gt;ICU’s metaZones.txt</a> for a list of supported timezone IDs. Passing null disables timezone emulation.

Returns: Task — The viewport task.

View source

EmulateVisionDeficiencyAsync(VisionDeficiency)

Section titled “EmulateVisionDeficiencyAsync(VisionDeficiency)”
public override 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”).

View source

EvaluateExpressionOnNewDocumentAsync(string)

Section titled “EvaluateExpressionOnNewDocumentAsync(string)”
public override 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;");

View source

EvaluateFunctionOnNewDocumentAsync(string, params object[])

Section titled “EvaluateFunctionOnNewDocumentAsync(string, params object[])”
public override 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");

View source

protected override 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.

View source

public override 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.

View source

public override 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.

View source

public override 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.

View source

public override 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.

View source

public override 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.

View source

public override 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.

View source

public override 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.

View source

protected override 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.

View source

PerformScreenshotAsync(ScreenshotType, ScreenshotOptions)

Section titled “PerformScreenshotAsync(ScreenshotType, ScreenshotOptions)”
protected override 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.

View source

public override 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.

View source

public override 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.

View source

public override 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.

View source

RemoveScriptToEvaluateOnNewDocumentAsync(string)

Section titled “RemoveScriptToEvaluateOnNewDocumentAsync(string)”
public override 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.

View source

public override 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.

View source

public override Task SetBurstModeOffAsync()

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

Returns: Task — The burst mode off.

View source

public override 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.

View source

public override 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.

View source

public override 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.

View source

public override 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.

View source

public override 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.

View source

SetExtraHttpHeadersAsync(Dictionary<string, string>)

Section titled “SetExtraHttpHeadersAsync(Dictionary<string, string>)”
public override 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.

View source

public override 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.

View source

public override 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.

View source

public override 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.

View source

public override 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.

View source

public override 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.

View source

SetUserAgentAsync(string, UserAgentMetadata)

Section titled “SetUserAgentAsync(string, UserAgentMetadata)”
public override 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.

View source

public override 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’); }

View source

public override 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.

View source

public override 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.

View source

public override 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.

View source

public override 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.

View source

Made with love by Dario Kondratiuk