How to use AddChildFrame method of PuppeteerSharp.Frame class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Frame.AddChildFrame

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Frame.cs

Source: Frame.cs Github

copy
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Threading.Tasks;
5using Newtonsoft.Json.Linq;
6using PuppeteerSharp.Input;
7
8namespace PuppeteerSharp
9{
10    /// <summary>
11    /// Provides methods to interact with a single page frame in Chromium. One <see cref="Page"/> instance might have multiple <see cref="Frame"/> instances.
12    /// At every point of time, page exposes its current frame tree via the <see cref="Page.MainFrame"/> and <see cref="ChildFrames"/> properties.
13    ///
14    /// <see cref="Frame"/> object's lifecycle is controlled by three events, dispatched on the page object
15    /// - <see cref="Page.FrameAttached"/> - fires when the frame gets attached to the page. A Frame can be attached to the page only once
16    /// - <see cref="Page.FrameNavigated"/> - fired when the frame commits navigation to a different URL
17    /// - <see cref="Page.FrameDetached"/> - fired when the frame gets detached from the page.  A Frame can be detached from the page only once
18    /// </summary>
19    /// <example>
20    /// An example of dumping frame tree
21    /// <code>
22    /// <![CDATA[
23    /// var browser = await Puppeteer.LaunchAsync(new LaunchOptions());
24    /// var page = await browser.NewPageAsync();
25    /// await page.GoToAsync("https://www.google.com/chrome/browser/canary.html");
26    /// dumpFrameTree(page.MainFrame, string.Empty);
27    /// await browser.CloseAsync();
28    ///
29    /// void dumpFrameTree(Frame frame, string indent)
30    /// {
31    ///     Console.WriteLine(indent + frame.Url);
32    ///     foreach (var child in frame.ChildFrames)
33    ///     {
34    ///         dumpFrameTree(child, indent + "  ");
35    ///     }
36    /// }
37    /// ]]>
38    /// </code>
39    /// </example>
40    public class Frame
41    {
42        private readonly List<Frame> _childFrames = new();
43
44        internal Frame(FrameManager frameManager, Frame parentFrame, string frameId)
45        {
46            FrameManager = frameManager;
47            ParentFrame = parentFrame;
48            Id = frameId;
49
50            LifecycleEvents = new List<string>();
51
52            MainWorld = new DOMWorld(FrameManager, this, FrameManager.TimeoutSettings);
53            SecondaryWorld = new DOMWorld(FrameManager, this, FrameManager.TimeoutSettings);
54
55            if (parentFrame != null)
56            {
57                ParentFrame.AddChildFrame(this);
58            }
59        }
60
61        /// <summary>
62        /// Gets the child frames of the this frame
63        /// </summary>
64        public List<Frame> ChildFrames
65        {
66            get
67            {
68                lock (_childFrames)
69                {
70                    return _childFrames.ToList();
71                }
72            }
73        }
74
75        /// <summary>
76        /// Gets the frame's name attribute as specified in the tag
77        /// If the name is empty, returns the id attribute instead
78        /// </summary>
79        public string Name { get; private set; }
80
81        /// <summary>
82        /// Gets the frame's url
83        /// </summary>
84        public string Url { get; private set; }
85
86        /// <summary>
87        /// Gets a value indicating if the frame is detached or not
88        /// </summary>
89        public bool Detached { get; set; }
90
91        /// <summary>
92        /// Gets the parent frame, if any. Detached frames and main frames return <c>null</c>
93        /// </summary>
94        public Frame ParentFrame { get; private set; }
95
96        internal FrameManager FrameManager { get; }
97
98        internal string Id { get; set; }
99
100        internal string LoaderId { get; set; }
101
102        internal List<string> LifecycleEvents { get; }
103
104        internal string NavigationURL { get; private set; }
105
106        internal DOMWorld MainWorld { get; }
107
108        internal DOMWorld SecondaryWorld { get; }
109
110        /// <summary>
111        /// Navigates to an url
112        /// </summary>
113        /// <remarks>
114        /// <see cref="GoToAsync(string, int?, WaitUntilNavigation[])"/> will throw an error if:
115        /// - there's an SSL error (e.g. in case of self-signed certificates).
116        /// - target URL is invalid.
117        /// - the `timeout` is exceeded during navigation.
118        /// - the remote server does not respond or is unreachable.
119        /// - the main resource failed to load.
120        ///
121        /// <see cref="GoToAsync(string, int?, WaitUntilNavigation[])"/> will not throw an error when any valid HTTP status code is returned by the remote server,
122        /// including 404 "Not Found" and 500 "Internal Server Error".  The status code for such responses can be retrieved by calling <see cref="Response.Status"/>
123        ///
124        /// > **NOTE** <see cref="GoToAsync(string, int?, WaitUntilNavigation[])"/> either throws an error or returns a main resource response.
125        /// The only exceptions are navigation to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
126        ///
127        /// > **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>.
128        /// </remarks>
129        /// <param name="url">URL to navigate page to. The url should include scheme, e.g. https://.</param>
130        /// <param name="options">Navigation parameters.</param>
131        /// <returns>Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.</returns>
132        /// <seealso cref="GoToAsync(string, int?, WaitUntilNavigation[])"/>
133        public Task<Response> GoToAsync(string url, NavigationOptions options) => FrameManager.NavigateFrameAsync(this, url, options);
134
135        /// <summary>
136        /// Navigates to an url
137        /// </summary>
138        /// <param name="url">URL to navigate page to. The url should include scheme, e.g. https://.</param>
139        /// <param name="timeout">maximum navigation time in milliseconds. Defaults to 30 seconds. Pass 0
140        /// to disable timeout. The default value can be changed by using the <see cref="Page.DefaultNavigationTimeout"/>
141        /// property.</param>
142        /// <param name="waitUntil">When to consider navigation succeeded, defaults to <see cref="WaitUntilNavigation.Load"/>. Given an array of <see cref="WaitUntilNavigation"/>, navigation is considered to be successful after all events have been fired</param>
143        /// <returns>Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect</returns>
144        public Task<Response> GoToAsync(string url, int? timeout = null, WaitUntilNavigation[] waitUntil = null)
145            => GoToAsync(url, new NavigationOptions { Timeout = timeout, WaitUntil = waitUntil });
146
147        /// <summary>
148        /// This resolves when the frame navigates to a new URL or reloads.
149        /// It is useful for when you run code which will indirectly cause the frame to navigate.
150        /// </summary>
151        /// <param name="options">navigation options</param>
152        /// <returns>Task which resolves to the main resource response.
153        /// In case of multiple redirects, the navigation will resolve with the response of the last redirect.
154        /// In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with `null`.
155        /// </returns>
156        /// <remarks>
157        /// Usage of the <c>History API</c> <see href="https://developer.mozilla.org/en-US/docs/Web/API/History_API"/> to change the URL is considered a navigation
158        /// </remarks>
159        /// <example>
160        /// <code>
161        /// <![CDATA[
162        /// var navigationTask =frame.page.WaitForNavigationAsync();
163        /// await frame.ClickAsync("a.my-link");
164        /// await navigationTask;
165        /// ]]>
166        /// </code>
167        /// </example>
168        public Task<Response> WaitForNavigationAsync(NavigationOptions options = null) => FrameManager.WaitForFrameNavigationAsync(this, options);
169
170        /// <summary>
171        /// Executes a script in browser context
172        /// </summary>
173        /// <param name="script">Script to be evaluated in browser context</param>
174        /// <remarks>
175        /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.
176        /// </remarks>
177        /// <returns>Task which resolves to script return value</returns>
178        /// <seealso cref="EvaluateFunctionAsync{T}(string, object[])"/>
179        /// <seealso cref="Page.EvaluateExpressionAsync{T}(string)"/>
180        public Task<JToken> EvaluateExpressionAsync(string script) => MainWorld.EvaluateExpressionAsync(script);
181
182        /// <summary>
183        /// Executes a script in browser context
184        /// </summary>
185        /// <typeparam name="T">The type to deserialize the result to</typeparam>
186        /// <param name="script">Script to be evaluated in browser context</param>
187        /// <remarks>
188        /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.
189        /// </remarks>
190        /// <returns>Task which resolves to script return value</returns>
191        /// <seealso cref="EvaluateFunctionAsync{T}(string, object[])"/>
192        /// <seealso cref="Page.EvaluateExpressionAsync{T}(string)"/>
193        public Task<T> EvaluateExpressionAsync<T>(string script) => MainWorld.EvaluateExpressionAsync<T>(script);
194
195        /// <summary>
196        /// Executes a function in browser context
197        /// </summary>
198        /// <param name="script">Script to be evaluated in browser context</param>
199        /// <param name="args">Arguments to pass to script</param>
200        /// <remarks>
201        /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.
202        /// <see cref="JSHandle"/> instances can be passed as arguments
203        /// </remarks>
204        /// <returns>Task which resolves to script return value</returns>
205        /// <seealso cref="EvaluateExpressionAsync{T}(string)"/>
206        /// <seealso cref="Page.EvaluateFunctionAsync{T}(string, object[])"/>
207        public Task<JToken> EvaluateFunctionAsync(string script, params object[] args) => MainWorld.EvaluateFunctionAsync(script, args);
208
209        /// <summary>
210        /// Executes a function in browser context
211        /// </summary>
212        /// <typeparam name="T">The type to deserialize the result to</typeparam>
213        /// <param name="script">Script to be evaluated in browser context</param>
214        /// <param name="args">Arguments to pass to script</param>
215        /// <remarks>
216        /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.
217        /// <see cref="JSHandle"/> instances can be passed as arguments
218        /// </remarks>
219        /// <returns>Task which resolves to script return value</returns>
220        /// <seealso cref="EvaluateExpressionAsync{T}(string)"/>
221        /// <seealso cref="Page.EvaluateFunctionAsync{T}(string, object[])"/>
222        public Task<T> EvaluateFunctionAsync<T>(string script, params object[] args) => MainWorld.EvaluateFunctionAsync<T>(script, args);
223
224        /// <summary>
225        /// Passes an expression to the <see cref="ExecutionContext.EvaluateExpressionHandleAsync(string)"/>, returns a <see cref="Task"/>, then <see cref="ExecutionContext.EvaluateExpressionHandleAsync(string)"/> would wait for the <see cref="Task"/> to resolve and return its value.
226        /// </summary>
227        /// <example>
228        /// <code>
229        /// var frame = page.MainFrame;
230        /// const handle = Page.MainFrame.EvaluateExpressionHandleAsync("1 + 2");
231        /// </code>
232        /// </example>
233        /// <returns>Resolves to the return value of <paramref name="script"/></returns>
234        /// <param name="script">Expression to be evaluated in the <seealso cref="ExecutionContext"/></param>
235        public Task<JSHandle> EvaluateExpressionHandleAsync(string script) => MainWorld.EvaluateExpressionHandleAsync(script);
236
237        /// <summary>
238        /// Passes a function to the <see cref="ExecutionContext.EvaluateFunctionAsync(string, object[])"/>, returns a <see cref="Task"/>, then <see cref="ExecutionContext.EvaluateFunctionHandleAsync(string, object[])"/> would wait for the <see cref="Task"/> to resolve and return its value.
239        /// </summary>
240        /// <example>
241        /// <code>
242        /// var frame = page.MainFrame;
243        /// const handle = Page.MainFrame.EvaluateFunctionHandleAsync("() => Promise.resolve(self)");
244        /// return handle; // Handle for the global object.
245        /// </code>
246        /// <see cref="JSHandle"/> instances can be passed as arguments to the <see cref="ExecutionContext.EvaluateFunctionAsync(string, object[])"/>:
247        ///
248        /// const handle = await Page.MainFrame.EvaluateExpressionHandleAsync("document.body");
249        /// const resultHandle = await Page.MainFrame.EvaluateFunctionHandleAsync("body => body.innerHTML", handle);
250        /// return await resultHandle.JsonValueAsync(); // prints body's innerHTML
251        /// </example>
252        /// <returns>Resolves to the return value of <paramref name="function"/></returns>
253        /// <param name="function">Function to be evaluated in the <see cref="ExecutionContext"/></param>
254        /// <param name="args">Arguments to pass to <paramref name="function"/></param>
255        public Task<JSHandle> EvaluateFunctionHandleAsync(string function, params object[] args) => MainWorld.EvaluateFunctionHandleAsync(function, args);
256
257        /// <summary>
258        /// Gets the <see cref="ExecutionContext"/> associated with the frame.
259        /// </summary>
260        /// <returns><see cref="ExecutionContext"/> associated with the frame.</returns>
261        public Task<ExecutionContext> GetExecutionContextAsync() => MainWorld.GetExecutionContextAsync();
262
263        /// <summary>
264        /// Waits for a selector to be added to the DOM
265        /// </summary>
266        /// <param name="selector">A selector of an element to wait for</param>
267        /// <param name="options">Optional waiting parameters</param>
268        /// <returns>A task that resolves when element specified by selector string is added to DOM.
269        /// Resolves to `null` if waiting for `hidden: true` and selector is not found in DOM.</returns>
270        /// <seealso cref="WaitForXPathAsync(string, WaitForSelectorOptions)"/>
271        /// <seealso cref="Page.WaitForSelectorAsync(string, WaitForSelectorOptions)"/>
272        /// <exception cref="WaitTaskTimeoutException">If timeout occurred.</exception>
273        public async Task<ElementHandle> WaitForSelectorAsync(string selector, WaitForSelectorOptions options = null)
274        {
275            var handle = await SecondaryWorld.WaitForSelectorAsync(selector, options).ConfigureAwait(false);
276            if (handle == null)
277            {
278                return null;
279            }
280            var mainExecutionContext = await MainWorld.GetExecutionContextAsync().ConfigureAwait(false);
281            var result = await mainExecutionContext.AdoptElementHandleAsync(handle).ConfigureAwait(false);
282            await handle.DisposeAsync().ConfigureAwait(false);
283            return result;
284        }
285
286        /// <summary>
287        /// Waits for a selector to be added to the DOM
288        /// </summary>
289        /// <param name="xpath">A xpath selector of an element to wait for</param>
290        /// <param name="options">Optional waiting parameters</param>
291        /// <returns>A task which resolves when element specified by xpath string is added to DOM.
292        /// Resolves to `null` if waiting for `hidden: true` and xpath is not found in DOM.</returns>
293        /// <example>
294        /// <code>
295        /// <![CDATA[
296        /// var browser = await Puppeteer.LaunchAsync(new LaunchOptions());
297        /// var page = await browser.NewPageAsync();
298        /// string currentURL = null;
299        /// page.MainFrame
300        ///     .WaitForXPathAsync("//img")
301        ///     .ContinueWith(_ => Console.WriteLine("First URL with image: " + currentURL));
302        /// foreach (var current in new[] { "https://example.com", "https://google.com", "https://bbc.com" })
303        /// {
304        ///     currentURL = current;
305        ///     await page.GoToAsync(currentURL);
306        /// }
307        /// await browser.CloseAsync();
308        /// ]]>
309        /// </code>
310        /// </example>
311        /// <seealso cref="WaitForSelectorAsync(string, WaitForSelectorOptions)"/>
312        /// <seealso cref="Page.WaitForXPathAsync(string, WaitForSelectorOptions)"/>
313        /// <exception cref="WaitTaskTimeoutException">If timeout occurred.</exception>
314        public async Task<ElementHandle> WaitForXPathAsync(string xpath, WaitForSelectorOptions options = null)
315        {
316            var handle = await SecondaryWorld.WaitForXPathAsync(xpath, options).ConfigureAwait(false);
317            if (handle == null)
318            {
319                return null;
320            }
321            var mainExecutionContext = await MainWorld.GetExecutionContextAsync().ConfigureAwait(false);
322            var result = await mainExecutionContext.AdoptElementHandleAsync(handle).ConfigureAwait(false);
323            await handle.DisposeAsync().ConfigureAwait(false);
324            return result;
325        }
326
327        /// <summary>
328        /// Waits for a timeout
329        /// </summary>
330        /// <param name="milliseconds">The amount of time to wait.</param>
331        /// <returns>A task that resolves when after the timeout</returns>
332        /// <seealso cref="Page.WaitForTimeoutAsync(int)"/>
333        /// <exception cref="WaitTaskTimeoutException">If timeout occurred.</exception>
334        public Task WaitForTimeoutAsync(int milliseconds) => Task.Delay(milliseconds);
335
336        /// <summary>
337        /// Waits for a function to be evaluated to a truthy value
338        /// </summary>
339        /// <param name="script">Function to be evaluated in browser context</param>
340        /// <param name="options">Optional waiting parameters</param>
341        /// <param name="args">Arguments to pass to <c>script</c></param>
342        /// <returns>A task that resolves when the <c>script</c> returns a truthy value</returns>
343        /// <seealso cref="Page.WaitForFunctionAsync(string, WaitForFunctionOptions, object[])"/>
344        /// <exception cref="WaitTaskTimeoutException">If timeout occurred.</exception>
345        public Task<JSHandle> WaitForFunctionAsync(string script, WaitForFunctionOptions options, params object[] args)
346        {
347            if (options == null)
348            {
349                throw new ArgumentNullException(nameof(options));
350            }
351
352            return MainWorld.WaitForFunctionAsync(script, options, args);
353        }
354
355        /// <summary>
356        /// Waits for an expression to be evaluated to a truthy value
357        /// </summary>
358        /// <param name="script">Expression to be evaluated in browser context</param>
359        /// <param name="options">Optional waiting parameters</param>
360        /// <returns>A task that resolves when the <c>script</c> returns a truthy value</returns>
361        /// <seealso cref="Page.WaitForExpressionAsync(string, WaitForFunctionOptions)"/>
362        /// <exception cref="WaitTaskTimeoutException">If timeout occurred.</exception>
363        public Task<JSHandle> WaitForExpressionAsync(string script, WaitForFunctionOptions options)
364        {
365            if (options == null)
366            {
367                throw new ArgumentNullException(nameof(options));
368            }
369
370            return MainWorld.WaitForExpressionAsync(script, options);
371        }
372
373        /// <summary>
374        /// Triggers a change and input event once all the provided options have been selected.
375        /// If there's no <![CDATA[<select>]]> element matching selector, the method throws an error.
376        /// </summary>
377        /// <exception cref="SelectorException">If there's no element matching <paramref name="selector"/></exception>
378        /// <param name="selector">A selector to query page for</param>
379        /// <param name="values">Values of options to select. If the <![CDATA[<select>]]> has the multiple attribute,
380        /// all values are considered, otherwise only the first one is taken into account.</param>
381        /// <returns>Returns an array of option values that have been successfully selected.</returns>
382        /// <seealso cref="Page.SelectAsync(string, string[])"/>
383        public Task<string[]> SelectAsync(string selector, params string[] values) => SecondaryWorld.SelectAsync(selector, values);
384
385        /// <summary>
386        /// Queries frame for the selector. If there's no such element within the frame, the method will resolve to <c>null</c>.
387        /// </summary>
388        /// <param name="selector">Selector to query frame for</param>
389        /// <returns>Task which resolves to <see cref="ElementHandle"/> pointing to the frame element</returns>
390        /// <seealso cref="Page.QuerySelectorAsync(string)"/>
391        public Task<ElementHandle> QuerySelectorAsync(string selector) => MainWorld.QuerySelectorAsync(selector);
392
393        /// <summary>
394        /// Queries frame for the selector. If no elements match the selector, the return value resolve to <see cref="Array.Empty{T}"/>.
395        /// </summary>
396        /// <param name="selector">A selector to query frame for</param>
397        /// <returns>Task which resolves to ElementHandles pointing to the frame elements</returns>
398        /// <seealso cref="Page.QuerySelectorAllAsync(string)"/>
399        public Task<ElementHandle[]> QuerySelectorAllAsync(string selector) => MainWorld.QuerySelectorAllAsync(selector);
400
401        /// <summary>
402        /// Evaluates the XPath expression
403        /// </summary>
404        /// <param name="expression">Expression to evaluate <see href="https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate"/></param>
405        /// <returns>Task which resolves to an array of <see cref="ElementHandle"/></returns>
406        /// <seealso cref="Page.XPathAsync(string)"/>
407        public Task<ElementHandle[]> XPathAsync(string expression) => MainWorld.XPathAsync(expression);
408
409        /// <summary>
410        /// Adds a <c><![CDATA[<link rel="stylesheet">]]></c> tag into the page with the desired url or a <c><![CDATA[<link rel="stylesheet">]]></c> tag with the content
411        /// </summary>
412        /// <param name="options">add style tag options</param>
413        /// <returns>Task which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame</returns>
414        /// <seealso cref="Page.AddStyleTagAsync(AddTagOptions)"/>
415        /// <seealso cref="Page.AddStyleTagAsync(string)"/>
416        [Obsolete("Use AddStyleTagAsync instead")]
417        public Task<ElementHandle> AddStyleTag(AddTagOptions options)
418        {
419            if (options == null)
420            {
421                throw new ArgumentNullException(nameof(options));
422            }
423
424            return MainWorld.AddStyleTagAsync(options);
425        }
426
427        /// <summary>
428        /// Adds a <c><![CDATA[<script>]]></c> tag into the page with the desired url or content
429        /// </summary>
430        /// <param name="options">add script tag options</param>
431        /// <returns>Task which resolves to the added tag when the script's onload fires or when the script content was injected into frame</returns>
432        /// <seealso cref="Page.AddScriptTagAsync(AddTagOptions)"/>
433        /// <seealso cref="Page.AddScriptTagAsync(string)"/>
434        [Obsolete("Use AddScriptTagAsync instead")]
435        public Task<ElementHandle> AddScriptTag(AddTagOptions options)
436        {
437            if (options == null)
438            {
439                throw new ArgumentNullException(nameof(options));
440            }
441
442            return MainWorld.AddScriptTagAsync(options);
443        }
444
445        /// <summary>
446        /// Adds a <c><![CDATA[<link rel="stylesheet">]]></c> tag into the page with the desired url or a <c><![CDATA[<link rel="stylesheet">]]></c> tag with the content
447        /// </summary>
448        /// <param name="options">add style tag options</param>
449        /// <returns>Task which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame</returns>
450        /// <seealso cref="Page.AddStyleTagAsync(AddTagOptions)"/>
451        /// <seealso cref="Page.AddStyleTagAsync(string)"/>
452        public Task<ElementHandle> AddStyleTagAsync(AddTagOptions options)
453        {
454            if (options == null)
455            {
456                throw new ArgumentNullException(nameof(options));
457            }
458
459            return MainWorld.AddStyleTagAsync(options);
460        }
461
462        /// <summary>
463        /// Adds a <c><![CDATA[<script>]]></c> tag into the page with the desired url or content
464        /// </summary>
465        /// <param name="options">add script tag options</param>
466        /// <returns>Task which resolves to the added tag when the script's onload fires or when the script content was injected into frame</returns>
467        /// <seealso cref="Page.AddScriptTagAsync(AddTagOptions)"/>
468        /// <seealso cref="Page.AddScriptTagAsync(string)"/>
469        public Task<ElementHandle> AddScriptTagAsync(AddTagOptions options)
470        {
471            if (options == null)
472            {
473                throw new ArgumentNullException(nameof(options));
474            }
475
476            return MainWorld.AddScriptTagAsync(options);
477        }
478
479        /// <summary>
480        /// Gets the full HTML contents of the page, including the doctype.
481        /// </summary>
482        /// <returns>Task which resolves to the HTML content.</returns>
483        /// <seealso cref="Page.GetContentAsync"/>
484        public Task<string> GetContentAsync() => SecondaryWorld.GetContentAsync();
485
486        /// <summary>
487        /// Sets the HTML markup to the page
488        /// </summary>
489        /// <param name="html">HTML markup to assign to the page.</param>
490        /// <param name="options">The options</param>
491        /// <returns>Task.</returns>
492        /// <seealso cref="Page.SetContentAsync(string, NavigationOptions)"/>
493        public Task SetContentAsync(string html, NavigationOptions options = null)
494            => SecondaryWorld.SetContentAsync(html, options);
495
496        /// <summary>
497        /// Returns page's title
498        /// </summary>
499        /// <returns>page's title</returns>
500        /// <seealso cref="Page.GetTitleAsync"/>
501        public Task<string> GetTitleAsync() => SecondaryWorld.GetTitleAsync();
502
503        /// <summary>
504        /// Fetches an element with <paramref name="selector"/>, scrolls it into view if needed, and then uses <see cref="Page.Mouse"/> to click in the center of the element.
505        /// </summary>
506        /// <param name="selector">A selector to search for element to click. If there are multiple elements satisfying the selector, the first will be clicked.</param>
507        /// <param name="options">click options</param>
508        /// <exception cref="SelectorException">If there's no element matching <paramref name="selector"/></exception>
509        /// <returns>Task which resolves when the element matching <paramref name="selector"/> is successfully clicked</returns>
510        public Task ClickAsync(string selector, ClickOptions options = null)
511            => SecondaryWorld.ClickAsync(selector, options);
512
513        /// <summary>
514        /// Fetches an element with <paramref name="selector"/>, scrolls it into view if needed, and then uses <see cref="Page.Mouse"/> to hover over the center of the element.
515        /// </summary>
516        /// <param name="selector">A selector to search for element to hover. If there are multiple elements satisfying the selector, the first will be hovered.</param>
517        /// <exception cref="SelectorException">If there's no element matching <paramref name="selector"/></exception>
518        /// <returns>Task which resolves when the element matching <paramref name="selector"/> is successfully hovered</returns>
519        public Task HoverAsync(string selector) => SecondaryWorld.HoverAsync(selector);
520
521        /// <summary>
522        /// Fetches an element with <paramref name="selector"/> and focuses it
523        /// </summary>
524        /// <param name="selector">A selector to search for element to focus. If there are multiple elements satisfying the selector, the first will be focused.</param>
525        /// <exception cref="SelectorException">If there's no element matching <paramref name="selector"/></exception>
526        /// <returns>Task which resolves when the element matching <paramref name="selector"/> is successfully focused</returns>
527        public Task FocusAsync(string selector) => SecondaryWorld.FocusAsync(selector);
528
529        /// <summary>
530        /// Sends a <c>keydown</c>, <c>keypress</c>/<c>input</c>, and <c>keyup</c> event for each character in the text.
531        /// </summary>
532        /// <param name="selector">A selector of an element to type into. If there are multiple elements satisfying the selector, the first will be used.</param>
533        /// <param name="text">A text to type into a focused element</param>
534        /// <param name="options">The options to apply to the type operation.</param>
535        /// <exception cref="SelectorException">If there's no element matching <paramref name="selector"/></exception>
536        /// <remarks>
537        /// To press a special key, like <c>Control</c> or <c>ArrowDown</c> use <see cref="Keyboard.PressAsync(string, PressOptions)"/>
538        /// </remarks>
539        /// <example>
540        /// <code>
541        /// await frame.TypeAsync("#mytextarea", "Hello"); // Types instantly
542        /// await frame.TypeAsync("#mytextarea", "World", new TypeOptions { Delay = 100 }); // Types slower, like a user
543        /// </code>
544        /// </example>
545        /// <returns>Task</returns>
546        public Task TypeAsync(string selector, string text, TypeOptions options = null)
547             => SecondaryWorld.TypeAsync(selector, text, options);
548
549        internal void AddChildFrame(Frame frame)
550        {
551            lock (_childFrames)
552            {
553                _childFrames.Add(frame);
554            }
555        }
556
557        internal void RemoveChildFrame(Frame frame)
558        {
559            lock (_childFrames)
560            {
561                _childFrames.Remove(frame);
562            }
563        }
564
565        internal void OnLoadingStopped()
566        {
567            LifecycleEvents.Add("DOMContentLoaded");
568            LifecycleEvents.Add("load");
569        }
570
571        internal void OnLifecycleEvent(string loaderId, string name)
572        {
573            if (name == "init")
574            {
575                LoaderId = loaderId;
576                LifecycleEvents.Clear();
577            }
578            LifecycleEvents.Add(name);
579        }
580
581        internal void Navigated(FramePayload framePayload)
582        {
583            Name = framePayload.Name ?? string.Empty;
584            NavigationURL = framePayload.Url + framePayload.UrlFragment;
585            Url = framePayload.Url + framePayload.UrlFragment;
586        }
587
588        internal void NavigatedWithinDocument(string url) => Url = url;
589
590        internal void Detach()
591        {
592            Detached = true;
593            MainWorld.Detach();
594            SecondaryWorld.Detach();
595            if (ParentFrame != null)
596            {
597                ParentFrame.RemoveChildFrame(this);
598            }
599            ParentFrame = null;
600        }
601    }
602}
603
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)