Table of Contents

Interface IFrame

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 interface IFrame

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.

IReadOnlyCollection<IFrame> ChildFrames { get; }

Property Value

IReadOnlyCollection<IFrame>

Detached

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

bool Detached { get; }

Property Value

bool

Id

Frame Id.

string Id { get; }

Property Value

string

Name

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

[Obsolete("Use (await frame.FrameElementAsync()).EvaluateFunctionAsync<string>(\"frame => frame.name\") instead.")]
string Name { get; }

Property Value

string

Page

The IPage associated with the frame.

IPage Page { get; }

Property Value

IPage

ParentFrame

Gets the parent frame, if any. Detached frames and main frames return null.

IFrame ParentFrame { get; }

Property Value

IFrame

Url

Gets the frame's url.

string Url { get; }

Property Value

string

Methods

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.

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.

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.

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.

Task<JsonElement?> EvaluateExpressionAsync(string script)

Parameters

script string

Script to be evaluated in browser context.

Returns

Task<JsonElement?>

Task which resolves to script return value.

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)

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

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.

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

Parameters

script string

Script to be evaluated in browser context.

args object[]

Arguments to pass to script.

Returns

Task<JsonElement?>

Task which resolves to script return value.

Remarks

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

See Also

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

Executes a function in browser context.

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.

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

Parameters

func string

Function to be evaluated in the ExecutionContext.

args object[]

Arguments to pass to func.

Returns

Task<IJSHandle>

Resolves to the return value of func.

Examples

var handle = await Page.MainFrame.EvaluateFunctionHandleAsync("() => Promise.resolve(self)");
return handle; // Handle for the global object.

IJSHandle instances can be passed as arguments to the EvaluateFunctionAsync(string, params object[]):

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.

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

Task<ElementHandle> FrameElementAsync()

Returns

Task<ElementHandle>

Task which resolves to the frame element.

GetContentAsync(GetContentOptions)

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

Task<string> GetContentAsync(GetContentOptions options = null)

Parameters

options GetContentOptions

Options.

Returns

Task<string>

Task which resolves to the HTML content.

See Also

GetTitleAsync()

Returns page's title.

Task<string> GetTitleAsync()

Returns

Task<string>

page's title.

See Also

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.

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

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

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)

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.

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.

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.

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.

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

Task<DeviceRequestPrompt> WaitForDevicePromptAsync(WaitForOptions options = null)

Parameters

options WaitForOptions

Optional waiting parameters.

Returns

Task<DeviceRequestPrompt>

A task that resolves after the page gets the prompt.

Examples

WaitForExpressionAsync(string, WaitForFunctionOptions)

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

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.

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.

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 API https://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.

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.

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

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

Events

FrameSwappedByActivation

Raised when the frame is swapped.

event EventHandler FrameSwappedByActivation

Event Type

EventHandler