Skip to content

Frame

Namespace: PuppeteerSharp

public abstract class Frame : IFrame

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.

Inheritance: object

Implements: IFrame

Derived: BidiFrame, CdpFrame

Example

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 + " ");
}
}

View source

public abstract IReadOnlyCollection<IFrame> ChildFrames { get; }

Gets the child frames of the this frame.

Value: IReadOnlyCollection<IFrame>

View source

public abstract ICDPSession Client { get; protected set; }

Gets the CDPSession associated with this environment.

Value: ICDPSession

View source

public virtual bool Detached { get; }

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

Value: bool

View source

public string Id { get; }

Frame Id.

Value: string

View source

protected ILogger Logger { get; init; }

Logger.

Value: ILogger

View source

public string Name { get; }

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

Value: string

View source

public abstract IPage Page { get; }

The IPage associated with the frame.

Value: IPage

View source

public virtual string Url { get; }

Gets the frame’s url.

Value: string

View source

public event EventHandler FrameSwappedByActivation

Raised when the frame is swapped.

Value: EventHandler

View source

public Task<IElementHandle> AddScriptTagAsync(AddTagOptions options)

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

Parameters

Name Type Description
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.

View source

public abstract Task<IElementHandle> AddStyleTagAsync(AddTagOptions options)

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

Parameters

Name Type Description
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.

View source

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

Fetches an element with <code class=“paramref”>selector</code>, scrolls it into view if needed, and then uses Mouse to click in the center of the element.

Parameters

Name Type Description
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 <code class=“paramref”>selector</code> is successfully clicked.

Exceptions

Type Condition
SelectorException If there’s no element matching <code class=“paramref”>selector</code>.

View source

public Task EvaluateExpressionAsync(string script)

Executes a script in browser context.

Parameters

Name Type Description
script string Script to be evaluated in browser context.

Returns: Task — Task which resolves to script return value.

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

View source

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

Executes a script in browser context.

Type parameters

Name Description
T The type to deserialize the result to.

Parameters

Name Type Description
script string Script to be evaluated in browser context.

Returns: Task<T> — Task which resolves to script return value.

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

View source

public Task<IJSHandle> EvaluateExpressionHandleAsync(string script)

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

Parameters

Name Type Description
script string Expression to be evaluated in the. ExecutionContext

Returns: Task<IJSHandle> — Resolves to the return value of <code class=“paramref”>script</code>.

Example

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

View source

EvaluateFunctionAsync(string, params object[])

Section titled “EvaluateFunctionAsync(string, params object[])”
public Task EvaluateFunctionAsync(string script, params object[] args)

Executes a function in browser context.

Parameters

Name Type Description
script string Script to be evaluated in browser context.
args object[] Arguments to pass to script.

Returns: Task — Task which resolves to script return value.

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.

View source

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

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

Executes a function in browser context.

Type parameters

Name Description
T The type to deserialize the result to.

Parameters

Name Type Description
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.

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.

View source

EvaluateFunctionHandleAsync(string, params object[])

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

Passes a function to the Object%5b%5d), returns a Task, then Object%5b%5d) would wait for the Task to resolve and return its value.

Parameters

Name Type Description
function string
args object[] Arguments to pass to <code class=“paramref”>func</code>.

Returns: Task<IJSHandle> — Resolves to the return value of <code class=“paramref”>func</code>.

Example

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 Object%5b%5d):

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

View source

public abstract IReadOnlyList<Realm> ExtensionRealms()

Retrieves the list of extension realms within this frame.

Returns: IReadOnlyList<Realm> — A list of Realm instances representing extension execution contexts.

View source

public Task FocusAsync(string selector)

Fetches an element with <code class=“paramref”>selector</code> and focuses it.

Parameters

Name Type Description
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 <code class=“paramref”>selector</code> is successfully focused.

Exceptions

Type Condition
SelectorException If there’s no element matching <code class=“paramref”>selector</code>.

View source

public virtual Task<ElementHandle> FrameElementAsync()

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

Returns: Task<ElementHandle> — Task which resolves to the frame element.

View source

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

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

Parameters

Name Type Description
options GetContentOptions Options.

Returns: Task<string> — Task which resolves to the HTML content.

View source

protected abstract DeviceRequestPromptManager GetDeviceRequestPromptManager()

Gets the prompts manager for the current client.

Returns: DeviceRequestPromptManager — The DeviceRequestPromptManager.

View source

public Task<string> GetTitleAsync()

Returns page’s title.

Returns: Task<string> — page’s title.

View source

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

Navigates to an url.

Parameters

Name Type Description
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.

WaitUntilNavigation%5b%5d) 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.
  • the URL is blocked by blocklist/allowlist rules.

WaitUntilNavigation%5b%5d) 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 WaitUntilNavigation%5b%5d) 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"&gt;upstream issue</see>.

View source

GoToAsync(string, int?, WaitUntilNavigation[])

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

Navigates to an url.

Parameters

Name Type Description
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.

View source

public Task HoverAsync(string selector)

Fetches an element with <code class=“paramref”>selector</code>, scrolls it into view if needed, and then uses Mouse to hover over the center of the element.

Parameters

Name Type Description
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 <code class=“paramref”>selector</code> is successfully hovered.

Exceptions

Type Condition
SelectorException If there’s no element matching <code class=“paramref”>selector</code>.

View source

public Locator Locator(string selector)

Creates a locator for the provided selector. See Locator for details and supported actions.

Parameters

Name Type Description
selector string A selector to locate an element.

Returns: Locator — A locator for the provided selector.

View source

public Locator LocatorFunction(string func)

Creates a locator for the provided function. See Locator for details and supported actions.

Parameters

Name Type Description
func string A JavaScript function expression to evaluate.

Returns: Locator — A locator for the provided function.

View source

protected virtual void OnDetach()

Called when this frame is being detached. Subclasses can override to perform additional cleanup.

View source

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

Queries frame for the selector. If no elements match the selector, the return value resolve to Empty%60%601.

Parameters

Name Type Description
selector string A selector to query frame for.

Returns: Task<IElementHandle[]> — Task which resolves to ElementHandles pointing to the frame elements.

View source

QuerySelectorAllAsync(string, QueryOptions)

Section titled “QuerySelectorAllAsync(string, QueryOptions)”
public Task<IElementHandle[]> QuerySelectorAllAsync(string selector, QueryOptions options)

Queries frame for the selector. If no elements match the selector, the return value resolve to Empty%60%601.

Parameters

Name Type Description
selector string A selector to query frame for.
options QueryOptions Optional query options.

Returns: Task<IElementHandle[]> — Task which resolves to ElementHandles pointing to the frame elements.

View source

public Task<IJSHandle> QuerySelectorAllHandleAsync(string selector)

A utility function to be used with Object%5b%5d).

Parameters

Name Type Description
selector string A selector to query page for.

Returns: Task<IJSHandle> — Task which resolves to a IJSHandle of document.querySelectorAll result.

View source

public Task<IElementHandle> QuerySelectorAsync(string selector)

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

Parameters

Name Type Description
selector string Selector to query frame for.

Returns: Task<IElementHandle> — Task which resolves to IElementHandle pointing to the frame element.

View source

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

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.

Parameters

Name Type Description
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

Type Condition
SelectorException If there’s no element matching <code class=“paramref”>selector</code>.

View source

SetContentAsync(string, NavigationOptions)

Section titled “SetContentAsync(string, NavigationOptions)”
[Obsolete("Use SetContentAsync(string, SetContentOptions) instead. The networkidle0 and networkidle2 wait conditions never worked reliably with SetContent.")]
public abstract Task SetContentAsync(string html, NavigationOptions options)

Sets the HTML markup to the page.

Parameters

Name Type Description
html string HTML markup to assign to the page.
options NavigationOptions The options.

Returns: Task — Task.

View source

SetContentAsync(string, SetContentOptions)

Section titled “SetContentAsync(string, SetContentOptions)”
public Task SetContentAsync(string html, SetContentOptions options = null)

Sets the HTML markup to the page.

Parameters

Name Type Description
html string HTML markup to assign to the page.
options SetContentOptions The options. The Networkidle0 and Networkidle2 wait conditions are not supported for SetContent.

Returns: Task — Task.

View source

public Task TapAsync(string selector)

Fetches an element with <code class=“paramref”>selector</code>, scrolls it into view if needed, and then uses Touchscreen to tap in the center of the element.

Parameters

Name Type Description
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 <code class=“paramref”>selector</code> is successfully tapped.

Exceptions

Type Condition
SelectorException If there’s no element matching <code class=“paramref”>selector</code>.

View source

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

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

Parameters

Name Type Description
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.

Exceptions

Type Condition
SelectorException If there’s no element matching <code class=“paramref”>selector</code>.

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

Example

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

View source

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

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.

Parameters

Name Type Description
options WaitForOptions Optional waiting parameters.

Returns: Task<DeviceRequestPrompt> — A task that resolves after the page gets the prompt.

Example

View source

WaitForExpressionAsync(string, WaitForFunctionOptions)

Section titled “WaitForExpressionAsync(string, WaitForFunctionOptions)”
public Task<IJSHandle> WaitForExpressionAsync(string script, WaitForFunctionOptions options)

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

Parameters

Name Type Description
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

Type Condition
WaitTaskTimeoutException If timeout occurred.

View source

WaitForFunctionAsync(string, WaitForFunctionOptions, params object[])

Section titled “WaitForFunctionAsync(string, WaitForFunctionOptions, params object[])”
public Task<IJSHandle> WaitForFunctionAsync(string script, WaitForFunctionOptions options, params object[] args)

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

Parameters

Name Type Description
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

Type Condition
WaitTaskTimeoutException If timeout occurred.

View source

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

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.

Parameters

Name Type Description
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.

Usage of the History API <a href=“https://developer.mozilla.org/en-US/docs/Web/API/History_API"&gt;https://developer.mozilla.org/en-US/docs/Web/API/History_API&lt;/a> to change the URL is considered a navigation.

Example

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

View source

WaitForSelectorAsync(string, WaitForSelectorOptions)

Section titled “WaitForSelectorAsync(string, WaitForSelectorOptions)”
public Task<IElementHandle> WaitForSelectorAsync(string selector, WaitForSelectorOptions options = null)

Waits for a selector to be added to the DOM.

Parameters

Name Type Description
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

Type Condition
WaitTaskTimeoutException If timeout occurred.

View source

WaitForXPathAsync(string, WaitForSelectorOptions)

Section titled “WaitForXPathAsync(string, WaitForSelectorOptions)”
public Task<IElementHandle> WaitForXPathAsync(string xpath, WaitForSelectorOptions options = null)

Waits for a selector to be added to the DOM.

Parameters

Name Type Description
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.

Exceptions

Type Condition
WaitTaskTimeoutException If timeout occurred.

Example

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

View source

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

Evaluates the XPath expression.

Parameters

Name Type Description
expression string Expression to evaluate <a href=“https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate"&gt;https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate&lt;/a>.

Returns: Task<IElementHandle[]> — Task which resolves to an array of IElementHandle.

View source

Made with love by Dario Kondratiuk