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
Properties
Browser
Browser.
protected abstract Browser Browser { get; }
Property Value
BrowserContext
Get the browser context that the page belongs to.
public abstract IBrowserContext BrowserContext { get; }
Property Value
Client
Supports all classes in the .NET class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all .NET classes; it is the root of the type hierarchy.
public abstract CDPSession Client { get; }
Property Value
DefaultNavigationTimeout
This setting will change the default maximum time for the following methods:
public int DefaultNavigationTimeout { get; set; }
Property Value
DefaultTimeout
This setting will change the default maximum times for the following methods:
- GoBackAsync(NavigationOptions)
- GoForwardAsync(NavigationOptions)
- GoToAsync(string, NavigationOptions)
- ReloadAsync(NavigationOptions)
- SetContentAsync(string, NavigationOptions)
- WaitForFunctionAsync(string, params object[])
- WaitForNavigationAsync(NavigationOptions)
- WaitForRequestAsync(string, WaitForOptions)
- WaitForResponseAsync(string, WaitForOptions)
- WaitForSelectorAsync(string, WaitForSelectorOptions)
- WaitForExpressionAsync(string, WaitForFunctionOptions).
public int DefaultTimeout { get; set; }
Property Value
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
IsClosed
Get an indication that the page has been closed.
public bool IsClosed { get; protected set; }
Property Value
IsDragInterceptionEnabled
true
if drag events are being intercepted, false
otherwise.
public bool IsDragInterceptionEnabled { get; protected set; }
Property Value
IsJavaScriptEnabled
If the page has JavaScript enabled.
public abstract bool IsJavaScriptEnabled { get; }
Property Value
IsServiceWorkerBypassed
true
if the service worker are being bypassed.
public bool IsServiceWorkerBypassed { get; protected set; }
Property Value
MainFrame
Gets page's main frame.
public abstract IFrame MainFrame { get; }
Property Value
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
ScreenshotBurstModeOptions
Screenshot burst mode options.
protected ScreenshotOptions ScreenshotBurstModeOptions { get; set; }
Property Value
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
TimeoutSettings
Timeout settings.
protected TimeoutSettings TimeoutSettings { get; set; }
Property Value
Url
Shortcut for page.MainFrame.Url
.
public string Url { get; }
Property Value
Viewport
Gets this page's viewport.
public ViewPortOptions Viewport { get; protected set; }
Property Value
Workers
Gets all workers in the page.
public abstract WebWorker[] Workers { get; }
Property Value
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
AddScriptTagAsync(AddTagOptions)
Adds a <script>
tag into the page with the desired url or content.
public Task<IElementHandle> AddScriptTagAsync(AddTagOptions options)
Parameters
options
AddTagOptionsadd 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
stringscript 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
AddTagOptionsadd 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
stringstylesheet 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
CredentialsThe 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
stringA selector to search for element to click. If there are multiple elements satisfying the selector, the first will be clicked.
options
ClickOptionsclick 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
PageCloseOptionsClose 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
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
DeviceDescriptorEmulation 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
EmulateIdleOverridesOverrides.
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
MediaTypeMedia 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
NetworkConditionsPassing
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
stringTimezone to set. See ICU’s
metaZones.txt
for a list of supported timezone IDs. Passingnull
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
VisionDeficiencyThe 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
stringScript 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
stringScript 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
stringScript to be evaluated in browser context.
Returns
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
stringJavascript 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
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
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
Returns
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
stringFunction 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
stringName of the function on the window object.
puppeteerFunction
ActionCallback 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
Returns
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
stringName 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
stringName 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
stringName 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
stringName 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
stringName 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
stringA 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
GetContentOptionsOptions.
Returns
- 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
GoBackAsync(NavigationOptions)
Navigate to the previous page in history.
public abstract Task<IResponse> GoBackAsync(NavigationOptions options = null)
Parameters
options
NavigationOptionsNavigation 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
NavigationOptionsNavigation 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
stringURL to navigate page to. The url should include scheme, e.g. https://.
options
NavigationOptionsNavigation 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
stringURL to navigate page to. The url should include scheme, e.g. https://.
waitUntil
WaitUntilNavigationWhen 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
stringURL 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
stringA 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
ConsoleEventArgsEvent args.
OnDOMContentLoaded()
Raises the DOMContentLoaded event.
protected void OnDOMContentLoaded()
OnError(ErrorEventArgs)
Raises the Error event.
protected void OnError(ErrorEventArgs e)
Parameters
e
ErrorEventArgsEvent args.
OnFrameAttached(FrameEventArgs)
Raises the FrameAttached event.
protected void OnFrameAttached(FrameEventArgs e)
Parameters
e
FrameEventArgsEvent arguments.
OnFrameDetached(FrameEventArgs)
Raises the FrameDetached event.
protected void OnFrameDetached(FrameEventArgs e)
Parameters
e
FrameEventArgsEvent arguments.
OnFrameNavigated(FrameNavigatedEventArgs)
Raises the FrameNavigated event.
protected void OnFrameNavigated(FrameNavigatedEventArgs e)
Parameters
e
FrameNavigatedEventArgsEvent arguments.
OnLoad()
Raises the Load event.
protected void OnLoad()
OnMetrics(MetricEventArgs)
Raises the Metrics event.
protected void OnMetrics(MetricEventArgs e)
Parameters
e
MetricEventArgsEvent args.
OnPageError(PageErrorEventArgs)
Raises the PageError event.
protected void OnPageError(PageErrorEventArgs e)
Parameters
e
PageErrorEventArgsEvent args.
OnRequest(IRequest)
Raises the Request event.
protected void OnRequest(IRequest request)
Parameters
request
IRequestRequest object.
OnRequestFailed(RequestEventArgs)
Raises the RequestFailed event.
protected void OnRequestFailed(RequestEventArgs e)
Parameters
e
RequestEventArgsEvent arguments.
OnRequestFinished(RequestEventArgs)
Raises the RequestFinished event.
protected void OnRequestFinished(RequestEventArgs e)
Parameters
e
RequestEventArgsEvent arguments.
OnRequestServedFromCache(RequestEventArgs)
Raises the RequestServedFromCache event.
protected void OnRequestServedFromCache(RequestEventArgs e)
Parameters
e
RequestEventArgsEvent arguments.
OnResponse(ResponseCreatedEventArgs)
Raises the Response event.
protected void OnResponse(ResponseCreatedEventArgs e)
Parameters
e
ResponseCreatedEventArgsEvent arguments.
OnWorkerCreated(WebWorker)
Raises the WorkerCreated event.
protected void OnWorkerCreated(WebWorker worker)
Parameters
worker
WebWorkerWorker.
OnWorkerDestroyed(WebWorker)
Raises the WorkerDestroyed event.
protected void OnWorkerDestroyed(WebWorker worker)
Parameters
worker
WebWorkerWorker.
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
stringThe 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
stringThe file path to save the PDF to. paths are resolved using GetFullPath(string).
options
PdfOptionspdf 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
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
PdfOptionspdf options.
Returns
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
stringFile path.
options
PdfOptionsPDF options.
Returns
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
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
PdfOptionspdf options.
Returns
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
ScreenshotTypeScreenshot type.
options
ScreenshotOptionsOptions.
Returns
QueryObjectsAsync(IJSHandle)
The method iterates JavaScript heap and finds all the objects with the given prototype.
Shortcut for page.MainFrame.GetExecutionContextAsync().QueryObjectsAsync(prototypeHandle)
.
public abstract Task<IJSHandle> QueryObjectsAsync(IJSHandle prototypeHandle)
Parameters
prototypeHandle
IJSHandleA handle to the object prototype.
Returns
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
stringA selector to query page for.
Returns
- Task<IElementHandle[]>
Task which resolves to ElementHandles pointing to the frame elements.
- See Also
QuerySelectorAllHandleAsync(string)
A utility function to be used with EvaluateFunctionAsync<T>(Task<IJSHandle>, string, params object[]).
public Task<IJSHandle> QuerySelectorAllHandleAsync(string selector)
Parameters
selector
stringA selector to query page for.
Returns
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
stringA 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
NavigationOptionsNavigation 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
stringName 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
RemoveScriptToEvaluateOnNewDocumentAsync(string)
Removes script that injected into page by EvaluateExpressionOnNewDocumentAsync(string) or EvaluateExpressionOnNewDocumentAsync(string).
public abstract Task RemoveScriptToEvaluateOnNewDocumentAsync(string identifier)
Parameters
identifier
stringFunction 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
stringThe 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
stringThe 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
ScreenshotOptionsScreenshot options.
Returns
- Task
The screenshot task.
ScreenshotBase64Async()
Takes a screenshot of the page.
public Task<string> ScreenshotBase64Async()
Returns
ScreenshotBase64Async(ScreenshotOptions)
Takes a screenshot of the page.
public Task<string> ScreenshotBase64Async(ScreenshotOptions options)
Parameters
options
ScreenshotOptionsScreenshot options.
Returns
ScreenshotDataAsync()
Takes a screenshot of the page.
public Task<byte[]> ScreenshotDataAsync()
Returns
ScreenshotDataAsync(ScreenshotOptions)
Takes a screenshot of the page.
public Task<byte[]> ScreenshotDataAsync(ScreenshotOptions options)
Parameters
options
ScreenshotOptionsScreenshot options.
Returns
ScreenshotStreamAsync()
Takes a screenshot of the page.
public Task<Stream> ScreenshotStreamAsync()
Returns
ScreenshotStreamAsync(ScreenshotOptions)
Takes a screenshot of the page.
public Task<Stream> ScreenshotStreamAsync(ScreenshotOptions options)
Parameters
options
ScreenshotOptionsScreenshot options.
Returns
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
stringA 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
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
boolsets 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
boolWhen
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
boolsets 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
stringHTML markup to assign to the page.
options
NavigationOptionsThe 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
boolInterception 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
GeolocationOptionGeolocation 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
boolWhether 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
boolWhen
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
boolWhether 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
stringSpecific user agent to use in this page.
userAgentData
UserAgentMetadataSpecific 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
ViewPortOptionsViewport 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
stringA 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
stringA selector of an element to type into. If there are multiple elements satisfying the selector, the first will be used.
text
stringA text to type into a focused element.
options
TypeOptionsThe 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
WaitForOptionsOptional 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
stringExpression to be evaluated in browser context.
options
WaitForFunctionOptionsOptional waiting parameters.
Returns
- See Also
WaitForFileChooserAsync(WaitForOptions)
Waits for a page to open a file picker.
public abstract Task<FileChooser> WaitForFileChooserAsync(WaitForOptions options = null)
Parameters
options
WaitForOptionsOptional 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
WaitForOptionsOptions.
Returns
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
stringFrame url.
options
WaitForOptionsOptions.
Returns
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
stringFunction to be evaluated in browser context.
options
WaitForFunctionOptionsOptional waiting parameters.
args
object[]Arguments to pass to
script
.
Returns
- 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
stringFunction to be evaluated in browser context.
args
object[]Arguments to pass to
script
.
Returns
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
NavigationOptionsnavigation 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.
public abstract Task WaitForNetworkIdleAsync(WaitForNetworkIdleOptions options = null)
Parameters
options
WaitForNetworkIdleOptionsOptional 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
WaitForOptionsOptions.
Returns
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
stringURL to wait for.
options
WaitForOptionsOptions.
Returns
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
WaitForOptionsOptions.
Returns
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
WaitForOptionsOptions.
Returns
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
stringURL to wait for.
options
WaitForOptionsOptions.
Returns
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
stringA selector of an element to wait for.
options
WaitForSelectorOptionsOptional waiting parameters.
Returns
- Task<IElementHandle>
A task that resolves when element specified by selector string is added to DOM. Resolves to
null
if waiting forhidden: 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
stringA xpath selector of an element to wait for.
options
WaitForSelectorOptionsOptional waiting parameters.
Returns
- Task<IElementHandle>
A task which resolves when element specified by xpath string is added to DOM. Resolves to
null
if waiting forhidden: 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
stringExpression 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
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
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.
public event EventHandler DOMContentLoaded
Event Type
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
Error
Raised when the page crashes
public event EventHandler<ErrorEventArgs> Error
Event Type
FrameAttached
Raised when a frame is attached.
public event EventHandler<FrameEventArgs> FrameAttached
Event Type
FrameDetached
Raised when a frame is detached.
public event EventHandler<FrameEventArgs> FrameDetached
Event Type
FrameNavigated
Raised when a frame is navigated to a new url.
public event EventHandler<FrameNavigatedEventArgs> FrameNavigated
Event Type
Load
Raised when the JavaScript load
https://developer.mozilla.org/en-US/docs/Web/Events/load event is dispatched.
public event EventHandler Load
Event Type
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
PageError
Raised when an uncaught exception happens within the page.
public event EventHandler<PageErrorEventArgs> PageError
Event Type
Popup
Raised when the page opens a new tab or window.
public event EventHandler<PopupEventArgs> Popup
Event Type
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
RequestFailed
Raised when a request fails, for example by timing out.
public event EventHandler<RequestEventArgs> RequestFailed
Event Type
RequestFinished
Raised when a request finishes successfully.
public event EventHandler<RequestEventArgs> RequestFinished
Event Type
RequestServedFromCache
Raised when a request ended up loading from cache.
public event EventHandler<RequestEventArgs> RequestServedFromCache
Event Type
Response
Raised when a Response is received.
public event EventHandler<ResponseCreatedEventArgs> Response
Event Type
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
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