Table of Contents

Class Frame

Namespace
PuppeteerSharp
Assembly
PuppeteerSharp.dll

Provides methods to interact with a single page frame in Chromium. One IPage instance might have multiple IFrame instances. At every point of time, page exposes its current frame tree via the MainFrame and ChildFrames properties.

IFrame object's lifecycle is controlled by three events, dispatched on the page object

  • FrameAttached - fires when the frame gets attached to the page. A Frame can be attached to the page only once
  • FrameNavigated - fired when the frame commits navigation to a different URL
  • FrameDetached - fired when the frame gets detached from the page. A Frame can be detached from the page only once.
public abstract class Frame : IFrame
Inheritance
Frame
Implements
Derived

Examples

An example of dumping frame tree.

var browser = await Puppeteer.LaunchAsync(new LaunchOptions());
var page = await browser.NewPageAsync();
await page.GoToAsync("https://www.google.com/chrome/browser/canary.html");
dumpFrameTree(page.MainFrame, string.Empty);
await browser.CloseAsync();

void dumpFrameTree(IFrame frame, string indent)
{
    Console.WriteLine(indent + frame.Url);
    foreach (var child in frame.ChildFrames)
    {
        dumpFrameTree(child, indent + "  ");
    }
}

Properties

ChildFrames

Gets the child frames of the this frame.

public abstract IReadOnlyCollection<IFrame> ChildFrames { get; }

Property Value

IReadOnlyCollection<IFrame>

Client

Gets the CDPSession associated with this environment.

public abstract CDPSession Client { get; protected set; }

Property Value

CDPSession

Detached

Gets a value indicating if the frame is detached or not.

public bool Detached { get; }

Property Value

bool

Id

Frame Id.

public string Id { get; }

Property Value

string

IsOopFrame

true if the frame is an OOP frame, or false otherwise.

public abstract bool IsOopFrame { get; }

Property Value

bool

Logger

Logger.

protected ILogger Logger { get; init; }

Property Value

ILogger

Name

Gets the frame's name attribute as specified in the tag If the name is empty, returns the id attribute instead.

public string Name { get; }

Property Value

string

Page

The IPage associated with the frame.

public abstract IPage Page { get; }

Property Value

IPage

Url

Gets the frame's url.

public string Url { get; }

Property Value

string

Methods

AddScriptTagAsync(AddTagOptions)

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

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

See Also

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

See Also

ClickAsync(string, ClickOptions)

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

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

Parameters

selector string

A selector to search for element to click. If there are multiple elements satisfying the selector, the first will be clicked.

options ClickOptions

click options.

Returns

Task

Task which resolves when the element matching selector is successfully clicked.

Exceptions

SelectorException

If there's no element matching selector.

EvaluateExpressionAsync(string)

Executes a script in browser context.

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

Remarks

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

See Also

EvaluateExpressionAsync<T>(string)

Executes a script in browser context.

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

Parameters

script string

Script to be evaluated in browser context.

Returns

Task<T>

Task which resolves to script return value.

Type Parameters

T

The type to deserialize the result to.

Remarks

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

See Also

EvaluateExpressionHandleAsync(string)

Passes an expression to the EvaluateExpressionHandleAsync(string), returns a Task, then EvaluateExpressionHandleAsync(string) would wait for the Task to resolve and return its value.

public Task<IJSHandle> EvaluateExpressionHandleAsync(string script)

Parameters

script string

Expression to be evaluated in the. ExecutionContext

Returns

Task<IJSHandle>

Resolves to the return value of script.

Examples

var handle = await Page.MainFrame.EvaluateExpressionHandleAsync("1 + 2");

EvaluateFunctionAsync(string, params object[])

Executes a function in browser context.

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

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

Parameters

script string

Script to be evaluated in browser context.

args object[]

Arguments to pass to script.

Returns

Task<T>

Task which resolves to script return value.

Type Parameters

T

The type to deserialize the result to.

Remarks

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

See Also

EvaluateFunctionHandleAsync(string, params object[])

Passes a function to the EvaluateFunctionAsync(string, params object[]), returns a Task, then EvaluateFunctionHandleAsync(string, params object[]) would wait for the Task to resolve and return its value.

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

Parameters

function string
args object[]

Arguments to pass to func.

Returns

Task<IJSHandle>

Resolves to the return value of func.

Examples

               <pre><code class="lang-csharp">var handle = await Page.MainFrame.EvaluateFunctionHandleAsync("() => Promise.resolve(self)");
               return handle; // Handle for the global object.</code></pre><xref href="PuppeteerSharp.IJSHandle" data-throw-if-not-resolved="false"></xref> instances can be passed as arguments to the <xref href="PuppeteerSharp.IExecutionContext.EvaluateFunctionAsync(System.String%2cSystem.Object%5b%5d)" data-throw-if-not-resolved="false"></xref>:
var handle = await Page.MainFrame.EvaluateExpressionHandleAsync("document.body");
var resultHandle = await Page.MainFrame.EvaluateFunctionHandleAsync("body => body.innerHTML", handle);
return await resultHandle.JsonValueAsync(); // prints body's innerHTML

FocusAsync(string)

Fetches an element with selector and focuses it.

public Task FocusAsync(string selector)

Parameters

selector string

A selector to search for element to focus. If there are multiple elements satisfying the selector, the first will be focused.

Returns

Task

Task which resolves when the element matching selector is successfully focused.

Exceptions

SelectorException

If there's no element matching selector.

FrameElementAsync()

The frame element associated with this frame (if any).

public Task<ElementHandle> FrameElementAsync()

Returns

Task<ElementHandle>

Task which resolves to the frame element.

GetContentAsync()

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

public Task<string> GetContentAsync()

Returns

Task<string>

Task which resolves to the HTML content.

See Also

GetDeviceRequestPromptManager()

Gets the prompts manager for the current client.

protected abstract DeviceRequestPromptManager GetDeviceRequestPromptManager()

Returns

DeviceRequestPromptManager

The DeviceRequestPromptManager.

GetTitleAsync()

Returns page's title.

public Task<string> GetTitleAsync()

Returns

Task<string>

page's title.

See Also

GoToAsync(string, NavigationOptions)

Navigates to an url.

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

Parameters

url string

URL to navigate page to. The url should include scheme, e.g. https://.

options NavigationOptions

Navigation parameters.

Returns

Task<IResponse>

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

Remarks

GoToAsync(string, int?, WaitUntilNavigation[]) will throw an error if: - there's an SSL error (e.g. in case of self-signed certificates). - target URL is invalid. - the timeout is exceeded during navigation. - the remote server does not respond or is unreachable. - the main resource failed to load.

 <xref href="PuppeteerSharp.IFrame.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.IFrame.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>.
See Also

GoToAsync(string, int?, WaitUntilNavigation[])

Navigates to an url.

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

Parameters

url string

URL to navigate page to. The url should include scheme, e.g. https://.

timeout int?

maximum navigation time in milliseconds. Defaults to 30 seconds. Pass 0 to disable timeout. The default value can be changed by using the DefaultNavigationTimeout property.

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.

HoverAsync(string)

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

public Task HoverAsync(string selector)

Parameters

selector string

A selector to search for element to hover. If there are multiple elements satisfying the selector, the first will be hovered.

Returns

Task

Task which resolves when the element matching selector is successfully hovered.

Exceptions

SelectorException

If there's no element matching selector.

QuerySelectorAllAsync(string)

Queries frame for the selector. If no elements match the selector, the return value resolve to Empty<T>().

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

Parameters

selector string

A selector to query frame for.

Returns

Task<IElementHandle[]>

Task which resolves to ElementHandles pointing to the frame elements.

See Also

QuerySelectorAllHandleAsync(string)

public Task<IJSHandle> QuerySelectorAllHandleAsync(string selector)

Parameters

selector string

A selector to query page for.

Returns

Task<IJSHandle>

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

QuerySelectorAsync(string)

Queries frame for the selector. If there's no such element within the frame, the method will resolve to null.

public Task<IElementHandle> QuerySelectorAsync(string selector)

Parameters

selector string

Selector to query frame for.

Returns

Task<IElementHandle>

Task which resolves to IElementHandle pointing to the frame element.

See Also

SelectAsync(string, params string[])

Triggers a change and input event once all the provided options have been selected. If there's no <select> element matching selector, the method throws an error.

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

Parameters

selector string

A selector to query page for.

values string[]

Values of options to select. If the <select> has the multiple attribute, all values are considered, otherwise only the first one is taken into account.

Returns

Task<string[]>

Returns an array of option values that have been successfully selected.

Exceptions

SelectorException

If there's no element matching selector.

See Also

SetContentAsync(string, NavigationOptions)

Sets the HTML markup to the page.

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

Parameters

html string

HTML markup to assign to the page.

options NavigationOptions

The options.

Returns

Task

Task.

See Also

TapAsync(string)

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

public Task TapAsync(string selector)

Parameters

selector string

A selector to search for element to tap. If there are multiple elements satisfying the selector, the first will be clicked.

Returns

Task

Task which resolves when the element matching selector is successfully tapped.

Exceptions

SelectorException

If there's no element matching selector.

TypeAsync(string, string, TypeOptions)

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

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

Parameters

selector string

A selector of an element to type into. If there are multiple elements satisfying the selector, the first will be used.

text string

A text to type into a focused element.

options TypeOptions

The options to apply to the type operation.

Returns

Task

Task.

Examples

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

Remarks

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

Exceptions

SelectorException

If there's no element matching selector.

WaitForDevicePromptAsync(WaitForOptions)

This method is typically coupled with an action that triggers a device request from an api such as WebBluetooth.

Caution.

This must be called before the device request is made. It will not return a currently active device prompt.

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

Parameters

options WaitForOptions

Optional waiting parameters.

Returns

Task<DeviceRequestPrompt>

A task that resolves after the page gets the prompt.

Examples

var promptTask = frame.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.

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

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.

Exceptions

WaitTaskTimeoutException

If timeout occurred.

See Also

WaitForFunctionAsync(string, WaitForFunctionOptions, params object[])

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

public Task<IJSHandle> WaitForFunctionAsync(string script, WaitForFunctionOptions options, 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.

Exceptions

WaitTaskTimeoutException

If timeout occurred.

See Also

WaitForNavigationAsync(NavigationOptions)

This resolves when the frame navigates to a new URL or reloads. It is useful for when you run code which will indirectly cause the frame to navigate.

public abstract 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.MainFrame.ClickAsync("a.my-link");
await navigationTask;

Remarks

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

WaitForSelectorAsync(string, WaitForSelectorOptions)

Waits for a selector to be added to the DOM.

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

Parameters

selector string

A selector of an element to wait for.

options WaitForSelectorOptions

Optional waiting parameters.

Returns

Task<IElementHandle>

A task that resolves when element specified by selector string is added to DOM. Resolves to null if waiting for hidden: true and selector is not found in DOM.

Exceptions

WaitTaskTimeoutException

If timeout occurred.

See Also

WaitForXPathAsync(string, WaitForSelectorOptions)

Waits for a selector to be added to the DOM.

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

Parameters

xpath string

A xpath selector of an element to wait for.

options WaitForSelectorOptions

Optional waiting parameters.

Returns

Task<IElementHandle>

A task which resolves when element specified by xpath string is added to DOM. Resolves to null if waiting for hidden: true and xpath is not found in DOM.

Examples

var browser = await Puppeteer.LaunchAsync(new LaunchOptions());
var page = await browser.NewPageAsync();
string currentURL = null;
page.MainFrame
    .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();

Exceptions

WaitTaskTimeoutException

If timeout occurred.

See Also

XPathAsync(string)

Evaluates the XPath expression.

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

Parameters

expression string

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

Returns

Task<IElementHandle[]>

Task which resolves to an array of IElementHandle.

Events

FrameSwappedByActivation

Raised when the frame is swapped.

public event EventHandler FrameSwappedByActivation

Event Type

EventHandler