Table of Contents

Interface IPage

Namespace
PuppeteerSharp
Assembly
PuppeteerSharp.dll

Provides methods to interact with a single tab in Chromium. One IBrowser instance might have multiple IPage instances.

public interface IPage : IDisposable, IAsyncDisposable

Examples

This example creates a page, navigates it to a URL, and then saves a screenshot:

var browser = await Puppeteer.LaunchAsync(new LaunchOptions());
var page = await browser.NewPageAsync();
await page.GoToAsync("https://example.com");
await page.ScreenshotAsync("screenshot.png");
await browser.CloseAsync();

Properties

Accessibility

Gets the accessibility.

IAccessibility Accessibility { get; }

Property Value

IAccessibility

Browser

Get the browser the page belongs to.

IBrowser Browser { get; }

Property Value

IBrowser

BrowserContext

Get the browser context that the page belongs to.

IBrowserContext BrowserContext { get; }

Property Value

IBrowserContext

Client

Chrome DevTools Protocol session.

ICDPSession Client { get; }

Property Value

ICDPSession

Coverage

Gets this page's coverage.

ICoverage Coverage { get; }

Property Value

ICoverage

DefaultNavigationTimeout

int DefaultNavigationTimeout { get; set; }

Property Value

int

DefaultTimeout

int DefaultTimeout { get; set; }

Property Value

int

Frames

Gets all frames attached to the page.

IFrame[] Frames { get; }

Property Value

IFrame[]

An array of all frames attached to the page.

IsClosed

Get an indication that the page has been closed.

bool IsClosed { get; }

Property Value

bool

IsDragInterceptionEnabled

true if drag events are being intercepted, false otherwise.

[Obsolete("We no longer support intercepting drag payloads. Use the new drag APIs found on ElementHandle to drag (or just use the Page.Mouse)")]
bool IsDragInterceptionEnabled { get; }

Property Value

bool

IsJavaScriptEnabled

If the page has JavaScript enabled.

bool IsJavaScriptEnabled { get; }

Property Value

bool

Keyboard

Gets this page's keyboard.

IKeyboard Keyboard { get; }

Property Value

IKeyboard

MainFrame

Gets page's main frame.

IFrame MainFrame { get; }

Property Value

IFrame

Remarks

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

Mouse

Gets this page's mouse.

IMouse Mouse { get; }

Property Value

IMouse

Target

Gets that target this page was created from.

[Obsolete("All the functionality provided by the Target should be already exposed by the page itself.")]
ITarget Target { get; }

Property Value

ITarget

Touchscreen

Gets this page's touchscreen.

ITouchscreen Touchscreen { get; }

Property Value

ITouchscreen

Tracing

Gets this page's tracing.

ITracing Tracing { get; }

Property Value

ITracing

Url

Shortcut for page.MainFrame.Url.

string Url { get; }

Property Value

string

Viewport

Gets this page's viewport.

ViewPortOptions Viewport { get; }

Property Value

ViewPortOptions

Workers

Gets all workers in the page.

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.

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.

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.

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.

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.

Task<IElementHandle> AddStyleTagAsync(string url)

Parameters

url string

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

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

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.

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.

Task CloseAsync(PageCloseOptions options = null)

Parameters

options PageCloseOptions

Close options.

Returns

Task

Task.

CreateCDPSessionAsync()

Creates a Chrome Devtools Protocol session attached to the page.

Task<ICDPSession> CreateCDPSessionAsync()

Returns

Task<ICDPSession>

A task that returns a ICDPSession.

DeleteCookieAsync(params CookieParam[])

Deletes cookies from the page.

Task DeleteCookieAsync(params CookieParam[] cookies)

Parameters

cookies CookieParam[]

Cookies to delete.

Returns

Task

Task.

EmulateAsync(DeviceDescriptor)

Emulates given device metrics and user agent.

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.

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.

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.

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.

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.

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.

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.

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.

Task<JToken> EvaluateExpressionAsync(string script)

Parameters

script string

Script to be evaluated in browser context.

Returns

Task<JToken>

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.

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.

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

Task<JToken> 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<JToken>

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.

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.

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

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

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.

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.

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.

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.

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.

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

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

Task<string> GetContentAsync()

Returns

Task<string>

Task which resolves to the HTML content.

See Also

GetCookiesAsync(params string[])

Returns the page's cookies.

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.

Task<string> GetTitleAsync()

Returns

Task<string>

page's title.

GoBackAsync(NavigationOptions)

Navigate to the previous page in history.

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.

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.

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.

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

Shortcut for. GoToAsync(string, int?, WaitUntilNavigation[])

See Also

GoToAsync(string, WaitUntilNavigation)

Navigates to an url.

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.

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.

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.

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.

PdfAsync(string)

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

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.

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.

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.

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.

PdfStreamAsync()

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

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.

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.

QueryObjectsAsync(IJSHandle)

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

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

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)

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.

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.

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.

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

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.

void RemoveRequestInterceptor(Func<IRequest, Task> interceptionTask)

Parameters

interceptionTask Func<IRequest, Task>

Interception task.

RemoveScriptToEvaluateOnNewDocumentAsync(string)

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.

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.

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.

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.

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.

Task<byte[]> ScreenshotDataAsync()

Returns

Task<byte[]>

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

ScreenshotDataAsync(ScreenshotOptions)

Takes a screenshot of the page.

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.

Task<Stream> ScreenshotStreamAsync()

Returns

Task<Stream>

Task which resolves to a Stream containing the image data.

ScreenshotStreamAsync(ScreenshotOptions)

Takes a screenshot of the page.

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.

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.

Task SetBurstModeOffAsync()

Returns

Task

The burst mode off.

SetBypassCSPAsync(bool)

Toggles bypassing page's Content-Security-Policy.

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.

SetCacheEnabledAsync(bool)

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

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.

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.

Task SetCookieAsync(params CookieParam[] cookies)

Parameters

cookies CookieParam[]

Cookies to set.

Returns

Task

Task.

SetDragInterceptionAsync(bool)

Whether to enable drag interception.

[Obsolete("We no longer support intercepting drag payloads. Use the new drag APIs found on ElementHandle to drag (or just use the Page.Mouse)")]
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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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

var promptTask = Page.WaitForDevicePromptAsync();
await Task.WhenAll(
    promptTask,
    Page.ClickAsync("#connect-bluetooth"));

var devicePrompt = await promptTask;
await devicePrompt.SelectAsync(
    await devicePrompt.WaitForDeviceAsync(device => device.Name.Contains("My Device")).ConfigureAwait(false)
);

WaitForExpressionAsync(string, WaitForFunctionOptions)

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

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.

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.

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.

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.

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.

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.

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

WaitForNetworkIdleAsync(WaitForNetworkIdleOptions)

Waits for Network Idle.

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.

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.

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.

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.

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.

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.

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

WaitForTimeoutAsync(int)

Waits for a timeout.

Task WaitForTimeoutAsync(int milliseconds)

Parameters

milliseconds int

The amount of time to wait.

Returns

Task

A task that resolves when after the timeout.

See Also

WaitForXPathAsync(string, WaitForSelectorOptions)

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

[Obsolete("Use WaitForSelectorAsync instead")]
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.

[Obsolete("Use QuerySelectorAsync instead")]
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.

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.

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 DOMContentLoaded https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded event is dispatched.

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.

event EventHandler<DialogEventArgs> Dialog

Event Type

EventHandler<DialogEventArgs>

Error

Raised when the page crashes

event EventHandler<ErrorEventArgs> Error

Event Type

EventHandler<ErrorEventArgs>

FrameAttached

Raised when a frame is attached.

event EventHandler<FrameEventArgs> FrameAttached

Event Type

EventHandler<FrameEventArgs>

FrameDetached

Raised when a frame is detached.

event EventHandler<FrameEventArgs> FrameDetached

Event Type

EventHandler<FrameEventArgs>

FrameNavigated

Raised when a frame is navigated to a new url.

event EventHandler<FrameEventArgs> FrameNavigated

Event Type

EventHandler<FrameEventArgs>

Load

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

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

event EventHandler<MetricEventArgs> Metrics

Event Type

EventHandler<MetricEventArgs>

PageError

Raised when an uncaught exception happens within the page.

event EventHandler<PageErrorEventArgs> PageError

Event Type

EventHandler<PageErrorEventArgs>

Popup

Raised when the page opens a new tab or window.

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)

event EventHandler<RequestEventArgs> Request

Event Type

EventHandler<RequestEventArgs>

RequestFailed

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

event EventHandler<RequestEventArgs> RequestFailed

Event Type

EventHandler<RequestEventArgs>

RequestFinished

Raised when a request finishes successfully.

event EventHandler<RequestEventArgs> RequestFinished

Event Type

EventHandler<RequestEventArgs>

RequestServedFromCache

Raised when a request ended up loading from cache.

event EventHandler<RequestEventArgs> RequestServedFromCache

Event Type

EventHandler<RequestEventArgs>

Response

Raised when a Response is received.

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.

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.

event EventHandler<WorkerEventArgs> WorkerDestroyed

Event Type

EventHandler<WorkerEventArgs>