Skip to content

Page

Namespace: PuppeteerSharp

public abstract class 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

Implements: IPage, IDisposable, IAsyncDisposable

Derived: BidiPage, CdpPage

View source

public static readonly IEnumerable<string> SupportedMetrics

List of supported metrics.

Value: IEnumerable<string>

View source

protected abstract Browser Browser { get; }

Browser.

Value: Browser

View source

public abstract IBrowserContext BrowserContext { get; }

Get the browser context that the page belongs to.

Value: IBrowserContext

View source

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

View source

public int DefaultNavigationTimeout { get; set; }

This setting will change the default maximum time for the following methods:

Value: int

View source

public int DefaultTimeout { get; set; }

This setting will change the default maximum times for the following methods:

Value: int

View source

public abstract IFrame[] Frames { get; }

Gets all frames attached to the page.

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

View source

protected bool HasConsoleEventListeners { get; }

Whether the Console event has listeners.

Value: bool

View source

public bool IsClosed { get; protected set; }

Get an indication that the page has been closed.

Value: bool

View source

public bool IsDragInterceptionEnabled { get; protected set; }

true if drag events are being intercepted, false otherwise.

Value: bool

View source

public abstract bool IsJavaScriptEnabled { get; }

If the page has JavaScript enabled.

Value: bool

View source

public bool IsServiceWorkerBypassed { get; protected set; }

true if the service worker are being bypassed.

Value: bool

View source

public abstract IFrame MainFrame { get; }

Gets page’s main frame.

Value: IFrame

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

View source

protected bool ScreenshotBurstModeOn { get; set; }

Whether burst mode is on.

Value: bool

View source

protected ScreenshotOptions ScreenshotBurstModeOptions { get; set; }

Screenshot burst mode options.

Value: ScreenshotOptions

View source

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

View source

public TimeoutSettings TimeoutSettings { get; set; }

Timeout settings.

Value: TimeoutSettings

View source

public string Url { get; }

Shortcut for page.MainFrame.Url.

Value: string

View source

public ViewPortOptions Viewport { get; protected set; }

Gets this page’s viewport.

Value: ViewPortOptions

View source

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.

View source

public abstract WebWorker[] Workers { get; }

Gets all workers in the page.

Value: WebWorker\[\]

View source

public event EventHandler Close

Raised when the page closes.

Value: EventHandler

View source

public event EventHandler<ConsoleEventArgs> Console

Raised 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]}");
}
}

View source

public event EventHandler DOMContentLoaded

Raised when the JavaScript DOMContentLoaded <a href=“https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded"&gt;https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded&lt;/a> event is dispatched.

Value: EventHandler

View source

public event EventHandler<DialogEventArgs> Dialog

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

View source

public event EventHandler<ErrorEventArgs> Error

Raised when the page crashes

Value: EventHandler<ErrorEventArgs>

View source

public event EventHandler<FrameEventArgs> FrameAttached

Raised when a frame is attached.

Value: EventHandler<FrameEventArgs>

View source

public event EventHandler<FrameEventArgs> FrameDetached

Raised when a frame is detached.

Value: EventHandler<FrameEventArgs>

View source

public event EventHandler<FrameNavigatedEventArgs> FrameNavigated

Raised when a frame is navigated to a new url.

Value: EventHandler<FrameNavigatedEventArgs>

View source

public event EventHandler<IssueEventArgs> Issue

Raised when a DevTools issue is reported.

Value: EventHandler<IssueEventArgs>

View source

public event EventHandler Load

Raised when the JavaScript load <a href=“https://developer.mozilla.org/en-US/docs/Web/Events/load"&gt;https://developer.mozilla.org/en-US/docs/Web/Events/load&lt;/a> event is dispatched.

Value: EventHandler

View source

public event EventHandler<MetricEventArgs> Metrics

Raised when the JavaScript code makes a call to console.timeStamp. For the list of metrics see MetricsAsync().

Value: EventHandler<MetricEventArgs>

View source

public event EventHandler<PageErrorEventArgs> PageError

Raised when an uncaught exception happens within the page.

Value: EventHandler<PageErrorEventArgs>

View source

public event EventHandler<PopupEventArgs> Popup

Raised when the page opens a new tab or window.

Value: EventHandler<PopupEventArgs>

View source

public event EventHandler<RequestEventArgs> Request

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

View source

public event EventHandler<RequestEventArgs> RequestFailed

Raised when a request fails, for example by timing out.

Value: EventHandler<RequestEventArgs>

View source

public event EventHandler<RequestEventArgs> RequestFinished

Raised when a request finishes successfully.

Value: EventHandler<RequestEventArgs>

View source

public event EventHandler<RequestEventArgs> RequestServedFromCache

Raised when a request ended up loading from cache.

Value: EventHandler<RequestEventArgs>

View source

public event EventHandler<ResponseCreatedEventArgs> Response

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

View source

public event EventHandler<WorkerEventArgs> WorkerCreated

Emitted when a dedicated WebWorker (<a href=“https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API"&gt;https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API&lt;/a>) is spawned by the page.

Value: EventHandler<WorkerEventArgs>

View source

public event EventHandler<WorkerEventArgs> WorkerDestroyed

Emitted when a dedicated WebWorker (<a href=“https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API"&gt;https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API&lt;/a>) is terminated.

Value: EventHandler<WorkerEventArgs>

View source

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.

View source

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

View source

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

View source

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

View source

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

View source

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

View source

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

View source

public abstract Task CloseAsync(PageCloseOptions options = null)

Closes the page.

Parameters

Name Type Description
options PageCloseOptions Close options.

Returns: Task — Task.

View source

public Task<ICDPSession> CreateCDPSessionAsync()

Creates a Chrome Devtools Protocol session attached to the page.

Returns: Task<ICDPSession> — A task that returns a ICDPSession.

View source

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.

View source

public abstract 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 void Dispose()

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

View source

protected virtual void Dispose(bool disposing)

Dispose resources.

Parameters

Name Type Description
disposing bool Indicates whether disposal was initiated by Dispose() operation.

View source

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.

View source

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

View source

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.

View source

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.

View source

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 emulation
await page.EmulateIdleStateAsync(new EmulateIdleOverrides() {IsUserActive = true, IsScreenUnlocked = false});
// do some checks here
...
// clear idle emulation
await page.EmulateIdleStateAsync();

View source

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.

View source

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

View source

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"&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 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”).

View source

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 objects

View source

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.

View source

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.

View source

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

View source

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.

View source

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.

View source

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.

View source

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

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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

View source

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.

View source

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.

View source

public Task<string> GetTitleAsync()

Returns page’s title.

Returns: Task<string> — page’s title.

View source

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.

View source

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.

View source

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 timeout is 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"&gt;upstream issue</see>.

Shortcut for. WaitUntilNavigation%5b%5d)

View source

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.

View source

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.

View source

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.

View source

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

View source

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.

View source

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.

View source

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.

View source

protected void OnClose()

Raises the Close event.

View source

protected void OnConsole(ConsoleEventArgs e)

Raises the Console event.

Parameters

Name Type Description
e ConsoleEventArgs Event args.

View source

protected void OnError(ErrorEventArgs e)

Raises the Error event.

Parameters

Name Type Description
e ErrorEventArgs Event args.

View source

protected void OnMetrics(MetricEventArgs e)

Raises the Metrics event.

Parameters

Name Type Description
e MetricEventArgs Event args.

View source

protected void OnPageError(PageErrorEventArgs e)

Raises the PageError event.

Parameters

Name Type Description
e PageErrorEventArgs Event args.

View source

protected void OnWorkerCreated(WebWorker worker)

Raises the WorkerCreated event.

Parameters

Name Type Description
worker WebWorker Worker.

View source

protected void OnWorkerDestroyed(WebWorker worker)

Raises the WorkerDestroyed event.

Parameters

Name Type Description
worker WebWorker Worker.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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

View source

[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"&gt;Page.startScreenRecording&lt;/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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

[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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

public Task<byte[]> ScreenshotDataAsync()

Takes a screenshot of the page.

Returns: Task<byte[]> — Task which resolves to a byte[] containing the image data.

View source

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.

View source

public Task<Stream> ScreenshotStreamAsync()

Takes a screenshot of the page.

Returns: Task<Stream> — Task which resolves to a Stream containing the image data.

View source

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.

View source

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

View source

public abstract Task SetBurstModeOffAsync()

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

Returns: Task — The burst mode off.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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.

View source

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

View source

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.

View source

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

View source

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.

View source

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 instantly
await page.TypeAsync("#mytextarea", "World", new TypeOptions { Delay = 100 }); // Types slower, like a user

View source

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

View source

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.

View source

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.

View source

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

View source

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

View source

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.

View source

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.

View source

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"&gt;https://developer.mozilla.org/en-US/docs/Web/API/History_API&lt;/a> to change the URL is considered a navigation.

Example

var navigationTask = page.WaitForNavigationAsync();
await page.ClickAsync("a.my-link");
await navigationTask;

View source

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 finishes

View source

WaitForRequestAsync(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;

View source

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;

View source

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;

View source

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;

View source

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;

View source

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.

View source

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

View source

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.

View source

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"&gt;https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate&lt;/a>.

Returns: Task<IElementHandle[]> — Task which resolves to an array of IElementHandle.

Shortcut for page.MainFrame.XPathAsync(expression).

View source

Made with love by Dario Kondratiuk