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
BrowserContext
Get the browser context that the page belongs to.
public override IBrowserContext BrowserContext { get; }
Property Value
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
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
MainFrame
Gets page's main frame.
public override IFrame MainFrame { get; }
Property Value
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
Workers
Gets all workers in the page.
public override WebWorker[] Workers { get; }
Property Value
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
credentialsCredentialsThe 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
optionsPageCloseOptionsClose options.
Returns
- Task
Task.
DeleteCookieAsync(params CookieParam[])
Deletes cookies from the page.
public override Task DeleteCookieAsync(params CookieParam[] cookies)
Parameters
cookiesCookieParam[]Cookies to delete.
Returns
- Task
Task.
EmulateCPUThrottlingAsync(decimal?)
Enables CPU throttling to emulate slow CPUs.
public override Task EmulateCPUThrottlingAsync(decimal? factor = null)
Parameters
factordecimal?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
overridesEmulateIdleOverrides
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
featuresIEnumerable<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
typeMediaTypeMedia 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
networkConditionsNetworkConditionsPassing
nulldisables 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
timezoneIdstringTimezone to set. See ICU’s
metaZones.txtfor a list of supported timezone IDs. Passingnulldisables timezone emulation.
Returns
- Task
The viewport task.
EmulateVisionDeficiencyAsync(VisionDeficiency)
Simulates the given vision deficiency on the page.
public override Task EmulateVisionDeficiencyAsync(VisionDeficiency type)
Parameters
typeVisionDeficiencyThe 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
expressionstringJavascript 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
pageFunctionstringFunction to be evaluated in browser context.
argsobject[]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
Returns
GetCookiesAsync(params string[])
Returns the page's cookies.
public override Task<CookieParam[]> GetCookiesAsync(params string[] urls)
Parameters
urlsstring[]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
optionsNavigationOptionsNavigation 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
optionsNavigationOptionsNavigation 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
filestringFile path.
optionsPdfOptionsPDF options.
Returns
PerformScreenshotAsync(ScreenshotType, ScreenshotOptions)
Screenshot implementation.
protected override Task<string> PerformScreenshotAsync(ScreenshotType type, ScreenshotOptions options)
Parameters
typeScreenshotTypeScreenshot type.
optionsScreenshotOptionsOptions.
Returns
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
prototypeHandleIJSHandleA handle to the object prototype.
Returns
ReloadAsync(NavigationOptions)
Reloads the page.
public override Task<IResponse> ReloadAsync(NavigationOptions options)
Parameters
optionsNavigationOptionsNavigation 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
namestringName of the function to remove.
Returns
- Task
Task.
RemoveScriptToEvaluateOnNewDocumentAsync(string)
Removes script that injected into page by EvaluateExpressionOnNewDocumentAsync(string) or EvaluateExpressionOnNewDocumentAsync(string).
public override Task RemoveScriptToEvaluateOnNewDocumentAsync(string identifier)
Parameters
identifierstringFunction 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
enabledboolsets 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
bypassboolWhen
truebypasses 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
enabledboolsets the
enabledstate 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
cookiesCookieParam[]Cookies to set.
Returns
- Task
Task.
SetDragInterceptionAsync(bool)
Whether to enable drag interception.
public override Task SetDragInterceptionAsync(bool enabled)
Parameters
enabledboolInterception 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
headersDictionary<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
optionsGeolocationOptionGeolocation 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
enabledboolWhether 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
valueboolWhen
trueenables 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
valueboolWhether 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
userAgentstringSpecific user agent to use in this page.
userAgentDataUserAgentMetadataSpecific 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
viewportViewPortOptionsViewport 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
optionsWaitForOptionsOptional 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
predicateFunc<IFrame, bool>Function which looks for a matching frame.
optionsWaitForOptionsOptions.
Returns
Examples
var frame = await page.WaitForFrameAsync(frame => frame.Name == "Test");
WaitForNetworkIdleAsync(WaitForNetworkIdleOptions)
Waits for Network Idle.
public override Task WaitForNetworkIdleAsync(WaitForNetworkIdleOptions options = null)
Parameters
optionsWaitForNetworkIdleOptionsOptional 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
predicateFunc<IRequest, bool>Function which looks for a matching request.
optionsWaitForOptionsOptions.
Returns
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
predicateFunc<IResponse, Task<bool>>Function which looks for a matching response.
optionsWaitForOptionsOptions.
Returns
Examples
var response = await page.WaitForResponseAsync(response => response.Url === "http://example.com" && response.Status === HttpStatus.Ok;
return response.Url;