Table of Contents

Class Page

Namespace
PuppeteerSharp
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 abstract class Page : IPage, IDisposable, IAsyncDisposable
Inheritance
Page
Implements
Derived

Fields

SupportedMetrics

List of supported metrics.

public static readonly IEnumerable<string> SupportedMetrics

Field Value

IEnumerable<string>

Properties

Browser

Browser.

protected abstract Browser Browser { get; }

Property Value

Browser

BrowserContext

Get the browser context that the page belongs to.

public abstract IBrowserContext BrowserContext { get; }

Property Value

IBrowserContext

Client

Supports all classes in the .NET class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all .NET classes; it is the root of the type hierarchy.

public abstract CDPSession Client { get; }

Property Value

CDPSession

DefaultNavigationTimeout

public int DefaultNavigationTimeout { get; set; }

Property Value

int

DefaultTimeout

public int DefaultTimeout { get; set; }

Property Value

int

Frames

Gets all frames attached to the page.

public abstract IFrame[] Frames { get; }

Property Value

IFrame[]

An array of all frames attached to the page.

HasConsoleEventListeners

Whether the Console event has listeners.

protected bool HasConsoleEventListeners { get; }

Property Value

bool

IsClosed

Get an indication that the page has been closed.

public bool IsClosed { get; protected set; }

Property Value

bool

IsDragInterceptionEnabled

true if drag events are being intercepted, false otherwise.

public bool IsDragInterceptionEnabled { get; protected set; }

Property Value

bool

IsJavaScriptEnabled

If the page has JavaScript enabled.

public abstract bool IsJavaScriptEnabled { get; }

Property Value

bool

IsServiceWorkerBypassed

true if the service worker are being bypassed.

public bool IsServiceWorkerBypassed { get; protected set; }

Property Value

bool

MainFrame

Gets page's main frame.

public abstract IFrame MainFrame { get; }

Property Value

IFrame

Remarks

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

ScreenshotBurstModeOn

Whether burst mode is on.

protected bool ScreenshotBurstModeOn { get; set; }

Property Value

bool

ScreenshotBurstModeOptions

Screenshot burst mode options.

protected ScreenshotOptions ScreenshotBurstModeOptions { get; set; }

Property Value

ScreenshotOptions

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 abstract Target Target { get; }

Property Value

Target

TimeoutSettings

Timeout settings.

protected TimeoutSettings TimeoutSettings { get; set; }

Property Value

TimeoutSettings

Url

Shortcut for page.MainFrame.Url.

public string Url { get; }

Property Value

string

Viewport

Gets this page's viewport.

public ViewPortOptions Viewport { get; protected set; }

Property Value

ViewPortOptions

Workers

Gets all workers in the page.

public abstract WebWorker[] Workers { get; }

Property Value

WebWorker[]

Methods

AddRequestInterceptor(Func<IRequest, Task>)

RespondAsync(ResponseData, int?), AbortAsync(RequestAbortErrorCode, int?), and ContinueAsync(Payload, int?) 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.

public void AddRequestInterceptor(Func<IRequest, Task> interceptionTask)

Parameters

interceptionTask Func<IRequest, Task>

Interception task.

AddScriptTagAsync(AddTagOptions)

Adds a <script> tag into the page with the desired url or content.

public Task<IElementHandle> AddScriptTagAsync(AddTagOptions options)

Parameters

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.

Remarks

Shortcut for page.MainFrame.AddScriptTagAsync(options).

See Also

AddScriptTagAsync(string)

Adds a <script> tag into the page with the desired url or content.

public Task<IElementHandle> AddScriptTagAsync(string url)

Parameters

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.

Remarks

Shortcut for page.MainFrame.AddScriptTagAsync(new AddTagOptions { Url = url }).

AddStyleTagAsync(AddTagOptions)

Adds a <link rel="stylesheet"> tag into the page with the desired url or a <link rel="stylesheet"> tag with the content.

public Task<IElementHandle> AddStyleTagAsync(AddTagOptions options)

Parameters

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.

Remarks

Shortcut for page.MainFrame.AddStyleTagAsync(options).

See Also

AddStyleTagAsync(string)

Adds a <link rel="stylesheet"> tag into the page with the desired url or a <link rel="stylesheet"> tag with the content.

public Task<IElementHandle> AddStyleTagAsync(string url)

Parameters

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.

Remarks

Shortcut for page.MainFrame.AddStyleTagAsync(new AddTagOptions { Url = url }).

AuthenticateAsync(Credentials)

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

public abstract Task AuthenticateAsync(Credentials credentials)

Parameters

credentials Credentials

The credentials.

Returns

Task

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

Remarks

To disable authentication, pass null.

BringToFrontAsync()

Brings page to front (activates tab).

public abstract Task BringToFrontAsync()

Returns

Task

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

ClickAsync(string, ClickOptions)

Fetches an element with selector, scrolls it into view if needed, and then uses Mouse to click in the center of the element.

public Task ClickAsync(string selector, ClickOptions options = null)

Parameters

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 selector is successfully clicked.

Exceptions

SelectorException

If there's no element matching selector.

CloseAsync(PageCloseOptions)

Closes the page.

public abstract Task CloseAsync(PageCloseOptions options = null)

Parameters

options PageCloseOptions

Close options.

Returns

Task

Task.

CreateCDPSessionAsync()

Creates a Chrome Devtools Protocol session attached to the page.

public Task<ICDPSession> CreateCDPSessionAsync()

Returns

Task<ICDPSession>

A task that returns a ICDPSession.

DeleteCookieAsync(params CookieParam[])

Deletes cookies from the page.

public abstract Task DeleteCookieAsync(params CookieParam[] cookies)

Parameters

cookies CookieParam[]

Cookies to delete.

Returns

Task

Task.

Dispose()

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

public void Dispose()

Dispose(bool)

Dispose resources.

protected virtual void Dispose(bool disposing)

Parameters

disposing bool

Indicates whether disposal was initiated by Dispose() operation.

DisposeAsync()

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

public ValueTask DisposeAsync()

Returns

ValueTask

A task that represents the asynchronous dispose operation.

EmulateAsync(DeviceDescriptor)

Emulates given device metrics and user agent.

public Task EmulateAsync(DeviceDescriptor options)

Parameters

options DeviceDescriptor

Emulation options.

Returns

Task

Task.

Examples

var iPhone = Puppeteer.Devices[DeviceDescriptorName.IPhone6]; using(var page = await browser.NewPageAsync()) { await page.EmulateAsync(iPhone); await page.goto('https://www.google.com'); }

Remarks

This method is a shortcut for calling two methods: SetViewportAsync(ViewPortOptions)SetUserAgentAsync(string, 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.

EmulateCPUThrottlingAsync(decimal?)

Enables CPU throttling to emulate slow CPUs.

public abstract Task EmulateCPUThrottlingAsync(decimal? factor = null)

Parameters

factor decimal?

Throttling rate as a slowdown factor (1 is no throttle, 2 is 2x slowdown, etc).

Returns

Task

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

EmulateIdleStateAsync(EmulateIdleOverrides)

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

public abstract Task EmulateIdleStateAsync(EmulateIdleOverrides idleOverrides = null)

Parameters

idleOverrides EmulateIdleOverrides

Overrides.

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 abstract Task EmulateMediaFeaturesAsync(IEnumerable<MediaFeatureValue> features)

Parameters

features IEnumerable<MediaFeatureValue>

Features to apply.

Returns

Task

Emulate features task.

Examples

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

EmulateMediaTypeAsync(MediaType)

Emulates a media such as screen or print.

public abstract Task EmulateMediaTypeAsync(MediaType type)

Parameters

type MediaType

Media to set.

Returns

Task

Emulate media type task.

Examples

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

EmulateNetworkConditionsAsync(NetworkConditions)

Emulates network conditions.

public abstract Task EmulateNetworkConditionsAsync(NetworkConditions networkConditions)

Parameters

networkConditions NetworkConditions

Passing null disables network condition emulation.

Returns

Task

Result task.

Remarks

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

EmulateTimezoneAsync(string)

Changes the timezone of the page.

public abstract Task EmulateTimezoneAsync(string timezoneId)

Parameters

timezoneId string

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

Returns

Task

The viewport task.

EmulateVisionDeficiencyAsync(VisionDeficiency)

Simulates the given vision deficiency on the page.

public abstract Task EmulateVisionDeficiencyAsync(VisionDeficiency type)

Parameters

type VisionDeficiency

The type of deficiency to simulate, or None to reset.

Returns

Task

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

Examples

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

EvaluateExpressionAsync(string)

Executes a script in browser context.

public Task<JsonElement?> EvaluateExpressionAsync(string script)

Parameters

script string

Script to be evaluated in browser context.

Returns

Task<JsonElement?>

Task which resolves to script return value.

Examples

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

Remarks

If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.

See Also

EvaluateExpressionAsync<T>(string)

Executes a script in browser context.

public Task<T> EvaluateExpressionAsync<T>(string script)

Parameters

script string

Script to be evaluated in browser context.

Returns

Task<T>

Task which resolves to script return value.

Type Parameters

T

The type to deserialize the result to.

Remarks

If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.

See Also

EvaluateExpressionHandleAsync(string)

Executes a script in browser context.

public Task<IJSHandle> EvaluateExpressionHandleAsync(string script)

Parameters

script string

Script to be evaluated in browser context.

Returns

Task<IJSHandle>

Task which resolves to script return value.

Remarks

If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.

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 abstract Task<NewDocumentScriptEvaluation> EvaluateExpressionOnNewDocumentAsync(string expression)

Parameters

expression string

Javascript expression to be evaluated in browser context.

Returns

Task<NewDocumentScriptEvaluation>

Task.

Examples

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

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

Remarks

The function is invoked after the document was created but before any of its scripts were run. This is useful to amend JavaScript environment, e.g. to seed Math.random.

EvaluateFunctionAsync(string, params object[])

Executes a function in browser context.

public Task<JsonElement?> EvaluateFunctionAsync(string script, params object[] args)

Parameters

script string

Script to be evaluated in browser context.

args object[]

Arguments to pass to script.

Returns

Task<JsonElement?>

Task which resolves to script return value.

Remarks

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.

See Also

EvaluateFunctionAsync<T>(string, params object[])

Executes a function in browser context.

public Task<T> EvaluateFunctionAsync<T>(string script, params object[] args)

Parameters

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.

Type Parameters

T

The type to deserialize the result to.

Remarks

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.

See Also

EvaluateFunctionHandleAsync(string, params object[])

Executes a script in browser context.

public Task<IJSHandle> EvaluateFunctionHandleAsync(string pageFunction, params object[] args)

Parameters

pageFunction string

Script to be evaluated in browser context.

args object[]

Function arguments.

Returns

Task<IJSHandle>

Task which resolves to script return value.

Remarks

If the script, returns a Promise, then the method would wait for the promise to resolve and return its value. IJSHandle instances can be passed as arguments.

EvaluateFunctionOnNewDocumentAsync(string, params object[])

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

Parameters

pageFunction string

Function to be evaluated in browser context.

args object[]

Arguments to pass to pageFunction.

Returns

Task<NewDocumentScriptEvaluation>

Task.

Examples

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

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

Remarks

The function is invoked after the document was created but before any of its scripts were run. This is useful to amend JavaScript environment, e.g. to seed Math.random.

ExposeFunctionAsync(string, Action)

Adds a function called name on the page's window object. When called, the function executes puppeteerFunction in C# and returns a Task which resolves when puppeteerFunction completes.

public Task ExposeFunctionAsync(string name, Action puppeteerFunction)

Parameters

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.

Remarks

If the puppeteerFunction returns a Task, it will be awaited. Functions installed via ExposeFunctionAsync(string, Action) survive navigations.

ExposeFunctionAsync(string, Delegate)

Internal add exposed functions.

protected abstract Task ExposeFunctionAsync(string name, Delegate puppeteerFunction)

Parameters

name string

Function name.

puppeteerFunction Delegate

Puppeteer function.

Returns

Task

A Task that completes when the function has been added.

ExposeFunctionAsync<TResult>(string, Func<TResult>)

Adds a function called name on the page's window object. When called, the function executes puppeteerFunction in C# and returns a Task which resolves to the return value of puppeteerFunction.

public Task ExposeFunctionAsync<TResult>(string name, Func<TResult> puppeteerFunction)

Parameters

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.

Type Parameters

TResult

The result of puppeteerFunction.

Remarks

If the puppeteerFunction returns a Task, it will be awaited. Functions installed via ExposeFunctionAsync<TResult>(string, Func<TResult>) survive navigations.

ExposeFunctionAsync<T, TResult>(string, Func<T, TResult>)

Adds a function called name on the page's window object. When called, the function executes puppeteerFunction in C# and returns a Task which resolves to the return value of puppeteerFunction.

public Task ExposeFunctionAsync<T, TResult>(string name, Func<T, TResult> puppeteerFunction)

Parameters

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.

Type Parameters

T

The parameter of puppeteerFunction.

TResult

The result of puppeteerFunction.

Remarks

If the puppeteerFunction returns a Task, it will be awaited. Functions installed via ExposeFunctionAsync<T, TResult>(string, Func<T, TResult>) survive navigations.

ExposeFunctionAsync<T1, T2, TResult>(string, Func<T1, T2, TResult>)

Adds a function called name on the page's window object. When called, the function executes puppeteerFunction in C# and returns a Task which resolves to the return value of puppeteerFunction.

public Task ExposeFunctionAsync<T1, T2, TResult>(string name, Func<T1, T2, TResult> puppeteerFunction)

Parameters

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.

Type Parameters

T1

The first parameter of puppeteerFunction.

T2

The second parameter of puppeteerFunction.

TResult

The result of puppeteerFunction.

Remarks

If the puppeteerFunction returns a Task, it will be awaited. Functions installed via ExposeFunctionAsync<T1, T2, TResult>(string, Func<T1, T2, TResult>) survive navigations.

ExposeFunctionAsync<T1, T2, T3, TResult>(string, Func<T1, T2, T3, TResult>)

Adds a function called name on the page's window object. When called, the function executes puppeteerFunction in C# and returns a Task which resolves to the return value of puppeteerFunction.

public Task ExposeFunctionAsync<T1, T2, T3, TResult>(string name, Func<T1, T2, T3, TResult> puppeteerFunction)

Parameters

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.

Type Parameters

T1

The first parameter of puppeteerFunction.

T2

The second parameter of puppeteerFunction.

T3

The third parameter of puppeteerFunction.

TResult

The result of puppeteerFunction.

Remarks

If the puppeteerFunction returns a Task, it will be awaited. Functions installed via ExposeFunctionAsync<T1, T2, T3, TResult>(string, Func<T1, T2, T3, TResult>) survive navigations.

ExposeFunctionAsync<T1, T2, T3, T4, TResult>(string, Func<T1, T2, T3, T4, TResult>)

Adds a function called name on the page's window object. When called, the function executes puppeteerFunction in C# and returns a Task which resolves to the return value of puppeteerFunction.

public Task ExposeFunctionAsync<T1, T2, T3, T4, TResult>(string name, Func<T1, T2, T3, T4, TResult> puppeteerFunction)

Parameters

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.

Type Parameters

T1

The first parameter of puppeteerFunction.

T2

The second parameter of puppeteerFunction.

T3

The third parameter of puppeteerFunction.

T4

The fourth parameter of puppeteerFunction.

TResult

The result of puppeteerFunction.

Remarks

If the puppeteerFunction returns a Task, it will be awaited. Functions installed via ExposeFunctionAsync<T1, T2, T3, T4, TResult>(string, Func<T1, T2, T3, T4, TResult>) survive navigations.

FocusAsync(string)

Fetches an element with selector and focuses it.

public Task FocusAsync(string selector)

Parameters

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 selector is successfully focused.

Exceptions

SelectorException

If there's no element matching selector.

GetContentAsync(GetContentOptions)

Gets the full HTML contents of the page, including the doctype.

public Task<string> GetContentAsync(GetContentOptions options = null)

Parameters

options GetContentOptions

Options.

Returns

Task<string>

Task which resolves to the HTML content.

See Also

GetCookiesAsync(params string[])

Returns the page's cookies.

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

Parameters

urls string[]

Url's to return cookies for.

Returns

Task<CookieParam[]>

Array of cookies.

Remarks

If no URLs are specified, this method returns cookies for the current page URL. If URLs are specified, only cookies for those URLs are returned.

GetTitleAsync()

Returns page's title.

public Task<string> GetTitleAsync()

Returns

Task<string>

page's title.

GoBackAsync(NavigationOptions)

Navigate to the previous page in history.

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

Parameters

options NavigationOptions

Navigation parameters.

Returns

Task<IResponse>

Task that resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go back, resolves to null.

GoForwardAsync(NavigationOptions)

Navigate to the next page in history.

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

Parameters

options NavigationOptions

Navigation parameters.

Returns

Task<IResponse>

Task that resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go forward, resolves to null.

GoToAsync(string, NavigationOptions)

Navigates to an url.

public Task<IResponse> GoToAsync(string url, NavigationOptions options)

Parameters

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.

Remarks

GoToAsync(string, int?, WaitUntilNavigation[]) 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.

 <xref href="PuppeteerSharp.IPage.GoToAsync(System.String%2cSystem.Nullable%7bSystem.Int32%7d%2cPuppeteerSharp.WaitUntilNavigation%5b%5d)" data-throw-if-not-resolved="false"></xref> 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 <xref href="PuppeteerSharp.IResponse.Status" data-throw-if-not-resolved="false"></xref>

 > **NOTE** <xref href="PuppeteerSharp.IPage.GoToAsync(System.String%2cSystem.Nullable%7bSystem.Int32%7d%2cPuppeteerSharp.WaitUntilNavigation%5b%5d)" data-throw-if-not-resolved="false"></xref> either throws an error or returns a main resource response.
 The only exceptions are navigation to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.

 > **NOTE** Headless mode doesn't support navigation to a PDF document. See the <see fref="https://bugs.chromium.org/p/chromium/issues/detail?id=761295">upstream issue</see>.

 Shortcut for. <xref href="PuppeteerSharp.IFrame.GoToAsync(System.String%2cSystem.Nullable%7bSystem.Int32%7d%2cPuppeteerSharp.WaitUntilNavigation%5b%5d)" data-throw-if-not-resolved="false"></xref>
See Also

GoToAsync(string, WaitUntilNavigation)

Navigates to an url.

public Task<IResponse> GoToAsync(string url, WaitUntilNavigation waitUntil)

Parameters

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.

See Also

GoToAsync(string, int?, WaitUntilNavigation[])

Navigates to an url.

public Task<IResponse> GoToAsync(string url, int? timeout = null, WaitUntilNavigation[] waitUntil = null)

Parameters

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.

See Also

HoverAsync(string)

Fetches an element with selector, scrolls it into view if needed, and then uses Mouse to hover over the center of the element.

public Task HoverAsync(string selector)

Parameters

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 selector is successfully hovered.

Exceptions

SelectorException

If there's no element matching selector.

MetricsAsync()

Returns metrics.

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

OnClose()

Raises the Close event.

protected void OnClose()

OnConsole(ConsoleEventArgs)

Raises the Console event.

protected void OnConsole(ConsoleEventArgs e)

Parameters

e ConsoleEventArgs

Event args.

OnDOMContentLoaded()

Raises the DOMContentLoaded event.

protected void OnDOMContentLoaded()

OnError(ErrorEventArgs)

Raises the Error event.

protected void OnError(ErrorEventArgs e)

Parameters

e ErrorEventArgs

Event args.

OnFrameAttached(FrameEventArgs)

Raises the FrameAttached event.

protected void OnFrameAttached(FrameEventArgs e)

Parameters

e FrameEventArgs

Event arguments.

OnFrameDetached(FrameEventArgs)

Raises the FrameDetached event.

protected void OnFrameDetached(FrameEventArgs e)

Parameters

e FrameEventArgs

Event arguments.

OnFrameNavigated(FrameNavigatedEventArgs)

Raises the FrameNavigated event.

protected void OnFrameNavigated(FrameNavigatedEventArgs e)

Parameters

e FrameNavigatedEventArgs

Event arguments.

OnLoad()

Raises the Load event.

protected void OnLoad()

OnMetrics(MetricEventArgs)

Raises the Metrics event.

protected void OnMetrics(MetricEventArgs e)

Parameters

e MetricEventArgs

Event args.

OnPageError(PageErrorEventArgs)

Raises the PageError event.

protected void OnPageError(PageErrorEventArgs e)

Parameters

e PageErrorEventArgs

Event args.

OnRequest(IRequest)

Raises the Request event.

protected void OnRequest(IRequest request)

Parameters

request IRequest

Request object.

OnRequestFailed(RequestEventArgs)

Raises the RequestFailed event.

protected void OnRequestFailed(RequestEventArgs e)

Parameters

e RequestEventArgs

Event arguments.

OnRequestFinished(RequestEventArgs)

Raises the RequestFinished event.

protected void OnRequestFinished(RequestEventArgs e)

Parameters

e RequestEventArgs

Event arguments.

OnRequestServedFromCache(RequestEventArgs)

Raises the RequestServedFromCache event.

protected void OnRequestServedFromCache(RequestEventArgs e)

Parameters

e RequestEventArgs

Event arguments.

OnResponse(ResponseCreatedEventArgs)

Raises the Response event.

protected void OnResponse(ResponseCreatedEventArgs e)

Parameters

e ResponseCreatedEventArgs

Event arguments.

OnWorkerCreated(WebWorker)

Raises the WorkerCreated event.

protected void OnWorkerCreated(WebWorker worker)

Parameters

worker WebWorker

Worker.

OnWorkerDestroyed(WebWorker)

Raises the WorkerDestroyed event.

protected void OnWorkerDestroyed(WebWorker worker)

Parameters

worker WebWorker

Worker.

PdfAsync(string)

generates a pdf of the page with Print css media. To generate a pdf with Screen media call EmulateMediaTypeAsync(MediaType) with Screen.

public Task PdfAsync(string file)

Parameters

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.

Remarks

Generating a pdf is currently only supported in Chrome headless.

PdfAsync(string, PdfOptions)

generates a pdf of the page with Print css media. To generate a pdf with Screen media call EmulateMediaTypeAsync(MediaType) with Screen.

public Task PdfAsync(string file, PdfOptions options)

Parameters

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.

Remarks

Generating a pdf is currently only supported in Chrome headless.

PdfDataAsync()

Generates a pdf of the page with Print css media. To generate a pdf with Screen media call EmulateMediaTypeAsync(MediaType) with Screen.

public Task<byte[]> PdfDataAsync()

Returns

Task<byte[]>

Task which resolves to a byte[] containing the PDF data.

Remarks

Generating a pdf is currently only supported in Chrome headless.

PdfDataAsync(PdfOptions)

Generates a pdf of the page with Print css media. To generate a pdf with Screen media call EmulateMediaTypeAsync(MediaType) with Screen.

public Task<byte[]> PdfDataAsync(PdfOptions options)

Parameters

options PdfOptions

pdf options.

Returns

Task<byte[]>

Task which resolves to a byte[] containing the PDF data.

Remarks

Generating a pdf is currently only supported in Chrome headless.

PdfInternalAsync(string, PdfOptions)

PDF implementation.

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

Parameters

file string

File path.

options PdfOptions

PDF options.

Returns

Task<byte[]>

PDF data.

PdfStreamAsync()

generates a pdf of the page with Print css media. To generate a pdf with Screen media call EmulateMediaTypeAsync(MediaType) with Screen.

public Task<Stream> PdfStreamAsync()

Returns

Task<Stream>

Task which resolves to a Stream containing the PDF data.

Remarks

Generating a pdf is currently only supported in Chrome headless.

PdfStreamAsync(PdfOptions)

Generates a pdf of the page with Print css media. To generate a pdf with Screen media call EmulateMediaTypeAsync(MediaType) with Screen.

public Task<Stream> PdfStreamAsync(PdfOptions options)

Parameters

options PdfOptions

pdf options.

Returns

Task<Stream>

Task which resolves to a Stream containing the PDF data.

Remarks

Generating a pdf is currently only supported in Chrome headless.

PerformScreenshotAsync(ScreenshotType, ScreenshotOptions)

Screenshot implementation.

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

Parameters

type ScreenshotType

Screenshot type.

options ScreenshotOptions

Options.

Returns

Task<string>

The screenshot as a base64 string.

QueryObjectsAsync(IJSHandle)

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

public abstract Task<IJSHandle> QueryObjectsAsync(IJSHandle prototypeHandle)

Parameters

prototypeHandle IJSHandle

A handle to the object prototype.

Returns

Task<IJSHandle>

A task which resolves to a handle to an array of objects with this prototype.

QuerySelectorAllAsync(string)

Runs document.querySelectorAll within the page. If no elements match the selector, the return value resolve to Empty<T>().

public Task<IElementHandle[]> QuerySelectorAllAsync(string selector)

Parameters

selector string

A selector to query page for.

Returns

Task<IElementHandle[]>

Task which resolves to ElementHandles pointing to the frame elements.

See Also

QuerySelectorAllHandleAsync(string)

public Task<IJSHandle> QuerySelectorAllHandleAsync(string selector)

Parameters

selector string

A selector to query page for.

Returns

Task<IJSHandle>

Task which resolves to a IJSHandle of document.querySelectorAll result.

QuerySelectorAsync(string)

The method runs document.querySelector within the page. If no element matches the selector, the return value resolve to null.

public Task<IElementHandle> QuerySelectorAsync(string selector)

Parameters

selector string

A selector to query page for.

Returns

Task<IElementHandle>

Task which resolves to IElementHandle pointing to the frame element.

Remarks

Shortcut for page.MainFrame.QuerySelectorAsync(selector).

See Also

ReloadAsync(NavigationOptions)

Reloads the page.

public abstract Task<IResponse> ReloadAsync(NavigationOptions options)

Parameters

options NavigationOptions

Navigation options.

Returns

Task<IResponse>

Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.

See Also

ReloadAsync(int?, WaitUntilNavigation[])

Reloads the page.

public Task<IResponse> ReloadAsync(int? timeout = null, WaitUntilNavigation[] waitUntil = null)

Parameters

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.

See Also

RemoveExposedFunctionAsync(string)

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

public abstract Task RemoveExposedFunctionAsync(string name)

Parameters

name string

Name of the function to remove.

Returns

Task

Task.

RemoveRequestInterceptor(Func<IRequest, Task>)

Removes a previously added request interceptor.

public void RemoveRequestInterceptor(Func<IRequest, Task> interceptionTask)

Parameters

interceptionTask Func<IRequest, Task>

Interception task.

RemoveScriptToEvaluateOnNewDocumentAsync(string)

public abstract Task RemoveScriptToEvaluateOnNewDocumentAsync(string identifier)

Parameters

identifier string

Function identifier.

Returns

Task

A task that resolves when the script is removed.

ScreenshotAsync(string)

Captures a screenshot of this IPage.

public Task ScreenshotAsync(string file)

Parameters

file string

The file path to save the image to. The screenshot type will be inferred from file extension. If path is a relative path, then it is resolved relative to current working directory. If no path is provided, the image won't be saved to the disk.

Returns

Task

The screenshot task.

ScreenshotAsync(string, ScreenshotOptions)

Takes a screenshot of the page.

public Task ScreenshotAsync(string file, ScreenshotOptions options)

Parameters

file string

The file path to save the image to. The screenshot type will be inferred from file extension. If path is a relative path, then it is resolved relative to current working directory. If no path is provided, the image won't be saved to the disk.

options ScreenshotOptions

Screenshot options.

Returns

Task

The screenshot task.

ScreenshotBase64Async()

Takes a screenshot of the page.

public Task<string> ScreenshotBase64Async()

Returns

Task<string>

Task which resolves to a string containing the image data as base64.

ScreenshotBase64Async(ScreenshotOptions)

Takes a screenshot of the page.

public Task<string> ScreenshotBase64Async(ScreenshotOptions options)

Parameters

options ScreenshotOptions

Screenshot options.

Returns

Task<string>

Task which resolves to a string containing the image data as base64.

ScreenshotDataAsync()

Takes a screenshot of the page.

public Task<byte[]> ScreenshotDataAsync()

Returns

Task<byte[]>

Task which resolves to a byte[] containing the image data.

ScreenshotDataAsync(ScreenshotOptions)

Takes a screenshot of the page.

public Task<byte[]> ScreenshotDataAsync(ScreenshotOptions options)

Parameters

options ScreenshotOptions

Screenshot options.

Returns

Task<byte[]>

Task which resolves to a byte[] containing the image data.

ScreenshotStreamAsync()

Takes a screenshot of the page.

public Task<Stream> ScreenshotStreamAsync()

Returns

Task<Stream>

Task which resolves to a Stream containing the image data.

ScreenshotStreamAsync(ScreenshotOptions)

Takes a screenshot of the page.

public Task<Stream> ScreenshotStreamAsync(ScreenshotOptions options)

Parameters

options ScreenshotOptions

Screenshot options.

Returns

Task<Stream>

Task which resolves to a Stream containing the image data.

SelectAsync(string, params string[])

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.

public Task<string[]> SelectAsync(string selector, params string[] values)

Parameters

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

SelectorException

If there's no element matching selector.

See Also

SetBurstModeOffAsync()

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

public abstract Task SetBurstModeOffAsync()

Returns

Task

The burst mode off.

SetBypassCSPAsync(bool)

Toggles bypassing page's Content-Security-Policy.

public abstract Task SetBypassCSPAsync(bool enabled)

Parameters

enabled bool

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

Returns

Task

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

Remarks

CSP bypassing happens at the moment of CSP initialization rather then evaluation. Usually this means that SetBypassCSPAsync(bool) should be called before navigating to the domain.

SetBypassServiceWorkerAsync(bool)

Toggles ignoring of service worker for each request.

public abstract Task SetBypassServiceWorkerAsync(bool bypass)

Parameters

bypass bool

When true bypasses service worker.

Returns

Task

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

SetCacheEnabledAsync(bool)

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

public abstract Task SetCacheEnabledAsync(bool enabled = true)

Parameters

enabled bool

sets the enabled state of the cache.

Returns

Task

Task.

SetContentAsync(string, NavigationOptions)

Sets the HTML markup to the page.

public Task SetContentAsync(string html, NavigationOptions options = null)

Parameters

html string

HTML markup to assign to the page.

options NavigationOptions

The navigations options.

Returns

Task

Task.

See Also

SetCookieAsync(params CookieParam[])

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

public abstract Task SetCookieAsync(params CookieParam[] cookies)

Parameters

cookies CookieParam[]

Cookies to set.

Returns

Task

Task.

SetDragInterceptionAsync(bool)

Whether to enable drag interception.

public abstract Task SetDragInterceptionAsync(bool enabled)

Parameters

enabled bool

Interception enabled.

Returns

Task

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

Remarks

Activating drag interception enables the Input.drag, methods This provides the capability to capture drag events emitted on the page, which can then be used to simulate drag-and-drop.

SetExtraHttpHeadersAsync(Dictionary<string, string>)

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

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

Parameters

headers Dictionary<string, string>

Additional http headers to be sent with every request.

Returns

Task

Task.

SetGeolocationAsync(GeolocationOption)

Sets the page's geolocation.

public abstract Task SetGeolocationAsync(GeolocationOption options)

Parameters

options GeolocationOption

Geolocation options.

Returns

Task

The task.

Remarks

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

SetJavaScriptEnabledAsync(bool)

Enables/Disables Javascript on the page.

public abstract Task SetJavaScriptEnabledAsync(bool enabled)

Parameters

enabled bool

Whether or not to enable JavaScript on the page.

Returns

Task

Task.

SetOfflineModeAsync(bool)

Set offline mode for the page.

public abstract Task SetOfflineModeAsync(bool value)

Parameters

value bool

When true enables offline mode for the page.

Returns

Task

Result task.

SetRequestInterceptionAsync(bool)

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

public abstract Task SetRequestInterceptionAsync(bool value)

Parameters

value bool

Whether to enable request interception..

Returns

Task

The request interception task.

SetUserAgentAsync(string, UserAgentMetadata)

Sets the user agent to be used in this page.

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

Parameters

userAgent string

Specific user agent to use in this page.

userAgentData UserAgentMetadata

Specific user agent client hint data to use in this page.

Returns

Task

Task.

SetViewportAsync(ViewPortOptions)

Sets the viewport. In the case of multiple pages in a single browser, each page can have its own viewport size. SetViewportAsync(ViewPortOptions) will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport before navigating to the page.

public abstract Task SetViewportAsync(ViewPortOptions viewport)

Parameters

viewport ViewPortOptions

Viewport options.

Returns

Task

The viewport task.

Examples

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

TapAsync(string)

Fetches an element with selector, scrolls it into view if needed, and then uses Touchscreen to tap in the center of the element.

public Task TapAsync(string selector)

Parameters

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 selector is successfully tapped.

Exceptions

SelectorException

If there's no element matching selector.

TypeAsync(string, string, TypeOptions)

Sends a keydown, keypress/input, and keyup event for each character in the text.

public Task TypeAsync(string selector, string text, TypeOptions options = null)

Parameters

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.

Examples

await page.TypeAsync("#mytextarea", "Hello"); // Types instantly
await page.TypeAsync("#mytextarea", "World", new TypeOptions { Delay = 100 }); // Types slower, like a user

Remarks

To press a special key, like Control or ArrowDown use PressAsync(string, PressOptions).

Exceptions

SelectorException

If there's no element matching selector.

WaitForDevicePromptAsync(WaitForOptions)

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.

public Task<DeviceRequestPrompt> WaitForDevicePromptAsync(WaitForOptions options = null)

Parameters

options WaitForOptions

Optional waiting parameters.

Returns

Task<DeviceRequestPrompt>

A task that resolves after the page gets the prompt.

Examples

WaitForExpressionAsync(string, WaitForFunctionOptions)

Waits for an expression to be evaluated to a truthy value.

public Task<IJSHandle> WaitForExpressionAsync(string script, WaitForFunctionOptions options = null)

Parameters

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.

See Also

WaitForFileChooserAsync(WaitForOptions)

Waits for a page to open a file picker.

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

Parameters

options WaitForOptions

Optional waiting parameters.

Returns

Task<FileChooser>

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

Examples

This method is typically coupled with an action that triggers file choosing. The following example clicks a button that issues a file chooser, and then responds with /tmp/myfile.pdf as if a user has selected this file.

var waitTask = page.WaitForFileChooserAsync();
await Task.WhenAll(
    waitTask,
    page.ClickAsync("#upload-file-button")); // some button that triggers file selection

await waitTask.Result.AcceptAsync('/tmp/myfile.pdf');

This must be called before the file chooser is launched. It will not return a currently active file chooser.

Remarks

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

WaitForFrameAsync(Func<IFrame, bool>, WaitForOptions)

Waits for a frame.

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

Parameters

predicate Func<IFrame, bool>

Function which looks for a matching frame.

options WaitForOptions

Options.

Returns

Task<IFrame>

A task which resolves when a matching frame was attached to the page.

Examples

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

WaitForFrameAsync(string, WaitForOptions)

Waits for a frame.

public Task<IFrame> WaitForFrameAsync(string url, WaitForOptions options = null)

Parameters

url string

Frame url.

options WaitForOptions

Options.

Returns

Task<IFrame>

A task which resolves when a matching frame was attached to the page.

Examples

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

WaitForFunctionAsync(string, WaitForFunctionOptions, params object[])

Waits for a function to be evaluated to a truthy value.

public Task<IJSHandle> WaitForFunctionAsync(string script, WaitForFunctionOptions options = null, params object[] args)

Parameters

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.

See Also

WaitForFunctionAsync(string, params object[])

Waits for a function to be evaluated to a truthy value.

public Task<IJSHandle> WaitForFunctionAsync(string script, params object[] args)

Parameters

script string

Function to be evaluated in browser context.

args object[]

Arguments to pass to script.

Returns

Task<IJSHandle>

A task that resolves when the script returns a truthy value.

WaitForNavigationAsync(NavigationOptions)

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.

public Task<IResponse> WaitForNavigationAsync(NavigationOptions options = null)

Parameters

options NavigationOptions

navigation options.

Returns

Task<IResponse>

Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with null.

Examples

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

Remarks

Usage of the History APIhttps://developer.mozilla.org/en-US/docs/Web/API/History_API to change the URL is considered a navigation.

WaitForNetworkIdleAsync(WaitForNetworkIdleOptions)

Waits for Network Idle.

public abstract Task WaitForNetworkIdleAsync(WaitForNetworkIdleOptions options = null)

Parameters

options WaitForNetworkIdleOptions

Optional waiting parameters.

Returns

Task

returns Task which resolves when network is idle.

Examples

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

WaitForRequestAsync(Func<IRequest, bool>, WaitForOptions)

Waits for a request.

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

Parameters

predicate Func<IRequest, bool>

Function which looks for a matching request.

options WaitForOptions

Options.

Returns

Task<IRequest>

A task which resolves when a matching request was made.

Examples

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

WaitForRequestAsync(string, WaitForOptions)

Waits for a request.

public Task<IRequest> WaitForRequestAsync(string url, WaitForOptions options = null)

Parameters

url string

URL to wait for.

options WaitForOptions

Options.

Returns

Task<IRequest>

A task which resolves when a matching request was made.

Examples

var firstRequest = await page.WaitForRequestAsync("http://example.com/resource");
return firstRequest.Url;

WaitForResponseAsync(Func<IResponse, bool>, WaitForOptions)

Waits for a response.

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

Parameters

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.

Examples

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

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

Waits for a response.

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

Parameters

predicate Func<IResponse, Task<bool>>

Function which looks for a matching response.

options WaitForOptions

Options.

Returns

Task<IResponse>

A task which resolves when a matching response is received.

Examples

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

WaitForResponseAsync(string, WaitForOptions)

Waits for a response.

public Task<IResponse> WaitForResponseAsync(string url, WaitForOptions options = null)

Parameters

url string

URL to wait for.

options WaitForOptions

Options.

Returns

Task<IResponse>

A task which resolves when a matching response is received.

Examples

var firstResponse = await page.WaitForResponseAsync("http://example.com/resource");
return firstResponse.Url;

WaitForSelectorAsync(string, WaitForSelectorOptions)

Waits for a selector to be added to the DOM.

public Task<IElementHandle> WaitForSelectorAsync(string selector, WaitForSelectorOptions options = null)

Parameters

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.

See Also

WaitForXPathAsync(string, WaitForSelectorOptions)

Waits for a xpath selector to be added to the DOM.

public Task<IElementHandle> WaitForXPathAsync(string xpath, WaitForSelectorOptions options = null)

Parameters

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.

Examples

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

XPathAsync(string)

Evaluates the XPath expression.

public Task<IElementHandle[]> XPathAsync(string expression)

Parameters

expression string

Expression to evaluate https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate.

Returns

Task<IElementHandle[]>

Task which resolves to an array of IElementHandle.

Remarks

Shortcut for page.MainFrame.XPathAsync(expression).

Events

Close

Raised when the page closes.

public event EventHandler Close

Event Type

EventHandler

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.

public event EventHandler<ConsoleEventArgs> Console

Event Type

EventHandler<ConsoleEventArgs>

Examples

An example of handling Console event:

page.Console += (sender, e) =>
{
    for (var i = 0; i < e.Message.Args.Count; ++i)
    {
        System.Console.WriteLine($"{i}: {e.Message.Args[i]}");
    }
}

DOMContentLoaded

Raised when the JavaScript DOMContentLoadedhttps://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded event is dispatched.

public event EventHandler DOMContentLoaded

Event Type

EventHandler

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.

public event EventHandler<DialogEventArgs> Dialog

Event Type

EventHandler<DialogEventArgs>

Error

Raised when the page crashes

public event EventHandler<ErrorEventArgs> Error

Event Type

EventHandler<ErrorEventArgs>

FrameAttached

Raised when a frame is attached.

public event EventHandler<FrameEventArgs> FrameAttached

Event Type

EventHandler<FrameEventArgs>

FrameDetached

Raised when a frame is detached.

public event EventHandler<FrameEventArgs> FrameDetached

Event Type

EventHandler<FrameEventArgs>

FrameNavigated

Raised when a frame is navigated to a new url.

public event EventHandler<FrameNavigatedEventArgs> FrameNavigated

Event Type

EventHandler<FrameNavigatedEventArgs>

Load

Raised when the JavaScript loadhttps://developer.mozilla.org/en-US/docs/Web/Events/load event is dispatched.

public event EventHandler Load

Event Type

EventHandler

Metrics

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

public event EventHandler<MetricEventArgs> Metrics

Event Type

EventHandler<MetricEventArgs>

PageError

Raised when an uncaught exception happens within the page.

public event EventHandler<PageErrorEventArgs> PageError

Event Type

EventHandler<PageErrorEventArgs>

Popup

Raised when the page opens a new tab or window.

public event EventHandler<PopupEventArgs> Popup

Event Type

EventHandler<PopupEventArgs>

Request

Raised when a page issues a request. The Request object is read-only. In order to intercept and mutate requests, see SetRequestInterceptionAsync(bool)

public event EventHandler<RequestEventArgs> Request

Event Type

EventHandler<RequestEventArgs>

RequestFailed

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

public event EventHandler<RequestEventArgs> RequestFailed

Event Type

EventHandler<RequestEventArgs>

RequestFinished

Raised when a request finishes successfully.

public event EventHandler<RequestEventArgs> RequestFinished

Event Type

EventHandler<RequestEventArgs>

RequestServedFromCache

Raised when a request ended up loading from cache.

public event EventHandler<RequestEventArgs> RequestServedFromCache

Event Type

EventHandler<RequestEventArgs>

Response

Raised when a Response is received.

public event EventHandler<ResponseCreatedEventArgs> Response

Event Type

EventHandler<ResponseCreatedEventArgs>

Examples

An example of handling Response event:

var tcs = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
page.Response += async(sender, e) =>
{
    if (e.Response.Url.Contains("script.js"))
    {
        tcs.TrySetResult(await e.Response.TextAsync());
    }
};

await Task.WhenAll(
    page.GoToAsync(TestConstants.ServerUrl + "/grid.html"),
    tcs.Task);
Console.WriteLine(await tcs.Task);

WorkerCreated

Emitted when a dedicated WebWorker (https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned by the page.

public event EventHandler<WorkerEventArgs> WorkerCreated

Event Type

EventHandler<WorkerEventArgs>

WorkerDestroyed

Emitted when a dedicated WebWorker (https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is terminated.

public event EventHandler<WorkerEventArgs> WorkerDestroyed

Event Type

EventHandler<WorkerEventArgs>