How to use PageWaitForPopupOptions method of Microsoft.Playwright.PageWaitForPopupOptions class

Best Playwright-dotnet code snippet using Microsoft.Playwright.PageWaitForPopupOptions.PageWaitForPopupOptions

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

PageWaitForPopupOptions.cs

Source: PageWaitForPopupOptions.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) Microsoft Corporation.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25using System;
26using System.Collections.Generic;
27using System.ComponentModel.DataAnnotations;
28using System.Drawing;
29using System.Globalization;
30using System.IO;
31using System.Runtime.Serialization;
32using System.Text.Json;
33using System.Text.Json.Serialization;
34using System.Text.RegularExpressions;
35using System.Threading;
36using System.Threading.Tasks;
37
38#nullable enable
39
40namespace Microsoft.Playwright
41{
42    public class PageWaitForPopupOptions
43    {
44        public PageWaitForPopupOptions() { }
45
46        public PageWaitForPopupOptions(PageWaitForPopupOptions clone)
47        {
48            if (clone == null)
49            {
50                return;
51            }
52
53            Predicate = clone.Predicate;
54            Timeout = clone.Timeout;
55        }
56
57        /// <summary>
58        /// <para>
59        /// Receives the <see cref="IPage"/> object and resolves to truthy value when the waiting
60        /// should resolve.
61        /// </para>
62        /// </summary>
63        [JsonPropertyName("predicate")]
64        public Func<IPage, bool>? Predicate { get; set; }
65
66        /// <summary>
67        /// <para>
68        /// Maximum time to wait for in milliseconds. Defaults to <c>30000</c> (30 seconds).
69        /// Pass <c>0</c> to disable timeout. The default value can be changed by using the
70        /// <see cref="IBrowserContext.SetDefaultTimeout"/>.
71        /// </para>
72        /// </summary>
73        [JsonPropertyName("timeout")]
74        public float? Timeout { get; set; }
75    }
76}
77
78#nullable disable
79
Full Screen

PageModel.cs

Source: PageModel.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) Evgeny Naazarchuk.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25using Microsoft.Playwright;
26using Playwright.Synchronous;
27using System;
28using System.Collections.Generic;
29using System.Text.RegularExpressions;
30using System.Threading.Tasks;
31
32namespace Playwright.PageObjectModel;
33
34public partial class PageModel : IPageModel
35{
36    public IPage Page { get; }
37
38    public PageModel(IPage page)
39    {
40        this.Page = page;
41    }
42
43    protected virtual void Wait() 
44    {
45    }
46
47    protected virtual void WaitForLoadState(LoadState loadState, PageWaitForLoadStateOptions? options = null)
48    {
49        this.Page.WaitForLoadState(loadState, options);
50    }
51
52    protected TPageModel CreatePageModel<TPageModel>()
53        where TPageModel : PageModel
54    {
55        var ctor = typeof(TPageModel).GetConstructor(new[] { typeof(IPage) });
56        if (ctor is null) throw new ApplicationException("Page Model not found");
57        var returnPage = ctor.Invoke(new[] { this.Page });
58        var page = (TPageModel)returnPage;
59
60        return page;
61    }
62
63    protected TBlockModel CreateBlockModel<TBlockModel>(string selector)
64        where TBlockModel : class
65    {
66        var blockType = typeof(TBlockModel);
67        var ctorArgs = new[] { this.GetType(), typeof(string) };
68
69        var ctor = blockType.GetConstructor(ctorArgs);
70        if (ctor is null) throw new ApplicationException("Block Model not found");
71
72        var block = ctor.Invoke(new[] { this, (object)selector });
73        if (block is null) throw new ApplicationException("Block Model not created");
74
75        return (TBlockModel)block;
76    }
77
78    protected TBlockModel CreateBlockModel<TBlockModel>(IElementHandle element)
79        where TBlockModel : class
80    {
81        var blockType = typeof(TBlockModel);
82        var ctorArgs = new[] { this.GetType(), typeof(IElementHandle) };
83
84        var ctor = blockType.GetConstructor(ctorArgs);
85        if (ctor is null) throw new ApplicationException("Block Model not found");
86
87        var block = ctor.Invoke(new[] { this, (object)element });
88        if (block is null) throw new ApplicationException("Block Model not created");
89
90        return (TBlockModel)block;
91    }
92
93    public virtual TPageModel Goto<TPageModel>(string url, PageGotoOptions? options = null)
94        where TPageModel : PageModel
95    {
96        this.Page.Goto(url, options);
97        var page = this.CreatePageModel<TPageModel>();
98        return page;
99    }
100
101    public virtual TPageModel GoBack<TPageModel>(PageGoBackOptions? options = null)
102        where TPageModel : PageModel
103    {
104        this.Page.GoBack(options);
105        var page = this.CreatePageModel<TPageModel>();
106        return page;
107    }
108
109    public virtual TPageModel GoForward<TPageModel>(PageGoForwardOptions? options = null)
110        where TPageModel : PageModel
111    {
112        this.Page.GoForward(options);
113        var page = this.CreatePageModel<TPageModel>();
114        return page;
115    }
116
117    public virtual TPageModel ReloadToPage<TPageModel>(PageReloadOptions? options = null)
118        where TPageModel : PageModel
119    {
120        this.Page.ReloadAsync(options).GetAwaiter().GetResult();
121        var page = this.CreatePageModel<TPageModel>();
122        return page;
123    }
124
125    public virtual void Close(PageCloseOptions? options = null)
126    {
127        this.Page.ClosePage(options);
128    }
129
130    protected virtual IElementHandle? QuerySelector(string selector, PageQuerySelectorOptions? options = null)
131    {
132        return this.Page.QuerySelector(selector, options);
133    }
134
135    protected virtual IReadOnlyList<IElementHandle> QuerySelectorAll(string selector)
136    {
137        return this.Page.QuerySelectorAll(selector);
138    }
139
140    protected virtual IElementHandle GetElement(
141        string selector,
142        PageWaitForSelectorOptions? waitOptions = null,
143        PageQuerySelectorOptions? queryOptions = null)
144    {
145        this.Page.WaitForSelector(selector, waitOptions);
146        var element = this.Page.QuerySelector(selector, queryOptions);
147        return element!;
148    }
149
150    protected virtual IReadOnlyCollection<IElementHandle> GetElements(string selector, PageWaitForSelectorOptions? waitOptions = null)
151    {
152        var elements = this.Page.QuerySelectorAll(selector);
153        return elements;
154    }
155
156    protected virtual TBlockModel GetElementModel<TBlockModel>(string selector, PageWaitForSelectorOptions? waitOptions = null)
157        where TBlockModel : class
158    {
159        var block = this.CreateBlockModel<TBlockModel>(selector);
160        return block;
161    }
162
163    protected virtual IReadOnlyCollection<TBlockModel> GetElementModels<TBlockModel>(string selector, PageWaitForSelectorOptions? waitOptions = null)
164        where TBlockModel : class
165    {
166        var elements = this.Page.QuerySelectorAll(selector);
167        var blocks = new List<TBlockModel>();
168
169        foreach (var element in elements)
170        {
171            var block = this.CreateBlockModel<TBlockModel>(element);
172            blocks.Add(block);
173        }
174
175        return blocks;
176    }
177
178    protected virtual IElementHandle? GetElementOrNull(
179        string selector,
180        PageWaitForSelectorOptions? waitOptions = null,
181        PageQuerySelectorOptions? queryOptions = null)
182    {
183        var element = this.Page.QuerySelector(selector, queryOptions);
184        return element;
185    }
186
187    protected virtual void Click(string selector, PageClickOptions? options = null)
188    {
189        this.Page.Click(selector, options);
190    }
191
192    protected virtual TReturnPage Click<TReturnPage>(string selector, PageClickOptions? options = null)
193        where TReturnPage : PageModel
194    {
195        this.Click(selector, options);
196        var page = this.CreatePageModel<TReturnPage>();
197        return page;
198    }
199
200    protected virtual void DblClick(string selector, PageDblClickOptions? options = null)
201    {
202        this.Page.DblClick(selector, options);
203    }
204
205    protected virtual void Type(string selector, string value, PageTypeOptions? options = null)
206    {
207        this.Page.Type(selector, value, options);
208    }
209
210    protected virtual void Check(string selector, PageCheckOptions? options = null)
211    {
212        this.Page.Check(selector, options);
213    }
214
215    protected virtual void Uncheck(string selector, PageUncheckOptions? options = null)
216    {
217        this.Page.Uncheck(selector, options);
218    }
219
220    protected virtual void SetChecked(string selector, bool checkedState, PageSetCheckedOptions? options = null)
221    {
222        this.Page.SetChecked(selector, checkedState, options);
223    }
224
225    protected virtual void Tap(string selector, PageTapOptions? options = null)
226    {
227        this.Page.Tap(selector, options);
228    }
229
230    protected virtual void DragAndDrop(string source, string target, PageDragAndDropOptions? options = null)
231    {
232        this.Page.DragAndDrop(source, target, options);
233    }
234
235    protected virtual void Focus(string selector, PageFocusOptions? options = null)
236    {
237        this.Page.Focus(selector, options);
238    }
239
240    protected virtual void Fill(string selector, string value, PageFillOptions? options = null)
241    {
242        this.Page.Fill(selector, value, options);
243    }
244
245    protected virtual void Hover(string selector, PageHoverOptions? options = null)
246    {
247        this.Page.Hover(selector, options);
248    }
249
250    protected virtual void Press(string selector, string key, PagePressOptions? options = null)
251    {
252        this.Page.Press(selector, key, options);
253    }
254
255    protected virtual IReadOnlyList<string> SelectOption(string selector, string values, PageSelectOptionOptions? options = null)
256    {
257        var result = this.Page.SelectOption(selector, values, options);
258        return result;
259    }
260
261    protected virtual IReadOnlyList<string> SelectOption(string selector, IElementHandle values, PageSelectOptionOptions? options = null)
262    {
263        var result = this.Page.SelectOption(selector, values, options);
264        return result;
265    }
266
267    protected virtual IReadOnlyList<string> SelectOption(string selector, IEnumerable<string> values, PageSelectOptionOptions? options = null)
268    {
269        var result = this.Page.SelectOption(selector, values, options);
270        return result;
271    }
272
273    protected virtual IReadOnlyList<string> SelectOption(string selector, SelectOptionValue values, PageSelectOptionOptions? options = null)
274    {
275        var result = this.Page.SelectOption(selector, values, options);
276        return result;
277    }
278
279    protected virtual IReadOnlyList<string> SelectOption(string selector, IEnumerable<IElementHandle> values, PageSelectOptionOptions? options = null)
280    {
281        var result = this.Page.SelectOption(selector, values, options);
282        return result;
283    }
284
285    protected virtual IReadOnlyList<string> SelectOption(string selector, IEnumerable<SelectOptionValue> values, PageSelectOptionOptions? options = null)
286    {
287        var result = this.Page.SelectOption(selector, values, options);
288        return result;
289    }
290
291    protected virtual void SetInputFiles(string selector, string files, PageSetInputFilesOptions? options = null)
292    {
293        this.Page.SetInputFiles(selector, files, options);
294    }
295
296    protected virtual void SetInputFiles(string selector, FilePayload files, PageSetInputFilesOptions? options = null)
297    {
298        this.Page.SetInputFiles(selector, files, options);
299    }
300
301    protected virtual void SetInputFiles(string selector, IEnumerable<string> files, PageSetInputFilesOptions? options = null)
302    {
303        this.Page.SetInputFiles(selector, files, options);
304    }
305
306    protected virtual void SetInputFiles(string selector, IEnumerable<FilePayload> files, PageSetInputFilesOptions? options = null)
307    {
308        this.Page.SetInputFiles(selector, files, options);
309    }
310
311    protected virtual void AddInitScript(string? script = null, string? scriptPath = null)
312    {
313        this.Page.AddInitScript(script, scriptPath);
314    }
315
316    protected virtual void AddScriptTag(PageAddScriptTagOptions? options = null)
317    {
318        this.Page.AddScriptTag(options);
319    }
320
321    protected virtual void AddStyleTag(PageAddStyleTagOptions? options = null)
322    {
323        this.Page.AddStyleTag(options);
324    }
325
326    protected virtual void BringToFront()
327    {
328        this.Page.BringToFront();
329    }
330
331    protected virtual string Content()
332    {
333        var content = this.Page.Content();
334        return content;
335    }
336
337    protected virtual void DispatchEvent(string selector, string type, object? eventInit = null, PageDispatchEventOptions? options = null)
338    {
339        this.Page.DispatchEvent(selector, type, eventInit, options); ;
340    }
341
342    protected virtual void EmulateMedia(PageEmulateMediaOptions? options = null)
343    {
344        this.Page.EmulateMedia(options);
345    }
346
347    protected virtual void EvalOnSelectorAll(string selector, string expression, object? arg = null)
348    {
349        this.Page.EvalOnSelectorAll(selector, expression, arg);
350    }
351
352    protected virtual void EvalOnSelectorAll<T>(string selector, string expression, object? arg = null)
353    {
354        this.Page.EvalOnSelectorAll<T>(selector, expression, arg);
355    }
356
357    protected virtual void EvalOnSelector(string selector, string expression, object? arg = null)
358    {
359        this.Page.EvalOnSelector(selector, expression, arg);
360    }
361
362    protected virtual void EvalOnSelector<T>(string selector, string expression, object? arg = null, PageEvalOnSelectorOptions? options = null)
363    {
364        this.Page.EvalOnSelector<T>(selector, expression, arg, options);
365    }
366
367    protected virtual void Evaluate(string expression, object? arg = null)
368    {
369        this.Page.Evaluate(expression, arg);
370    }
371
372    protected virtual void Evaluate<T>(string expression, object? arg = null)
373    {
374        this.Page.Evaluate<T>(expression, arg);
375    }
376
377    protected virtual void EvaluateHandle(string expression, object? arg = null)
378    {
379        this.Page.EvaluateHandle(expression, arg);
380    }
381
382    protected virtual void ExposeBinding(string name, Action<BindingSource> callback)
383    {
384        this.Page.ExposeBinding(name, callback);
385    }
386
387    protected virtual void ExposeBinding(string name, Action callback, PageExposeBindingOptions? options = null)
388    {
389        this.Page.ExposeBinding(name, callback, options);
390    }
391
392    protected virtual void ExposeBinding<T>(string name, Action<BindingSource, T> callback)
393    {
394        this.Page.ExposeBinding<T>(name, callback);
395    }
396
397    protected virtual void ExposeBinding<TResult>(string name, Func<BindingSource, TResult> callback)
398    {
399        this.Page.ExposeBinding<TResult>(name, callback);
400    }
401
402    protected virtual void ExposeBinding<TResult>(string name, Func<BindingSource, IJSHandle, TResult> callback)
403    {
404        this.Page.ExposeBinding<TResult>(name, callback);
405    }
406
407    protected virtual void ExposeBinding<T, TResult>(string name, Func<BindingSource, T, TResult> callback)
408    {
409        this.Page.ExposeBinding<T, TResult>(name, callback);
410    }
411
412    protected virtual void ExposeBinding<T1, T2, TResult>(string name, Func<BindingSource, T1, T2, TResult> callback)
413    {
414        this.Page.ExposeBinding<T1, T2, TResult>(name, callback);
415    }
416
417    protected virtual void ExposeBinding<T1, T2, T3, TResult>(string name, Func<BindingSource, T1, T2, T3, TResult> callback)
418    {
419        this.Page.ExposeBinding<T1, T2, T3, TResult>(name, callback);
420    }
421
422    protected virtual void ExposeBinding<T1, T2, T3, T4, TResult>(string name, Func<BindingSource, T1, T2, T3, T4, TResult> callback)
423    {
424        this.Page.ExposeBinding<T1, T2, T3, T4, TResult>(name, callback);
425    }
426
427    protected virtual void ExposeFunction(string name, Action callback)
428    {
429        this.Page.ExposeFunction(name, callback);
430    }
431
432    protected virtual void ExposeFunction<T>(string name, Action<T> callback)
433    {
434        this.Page.ExposeFunction<T>(name, callback);
435    }
436
437    protected virtual void ExposeFunction<TResult>(string name, Func<TResult> callback)
438    {
439        this.Page.ExposeFunction<TResult>(name, callback);
440    }
441
442    protected virtual void ExposeFunction<T, TResult>(string name, Func<T, TResult> callback)
443    {
444        this.Page.ExposeFunction<T, TResult>(name, callback);
445    }
446
447    protected virtual void ExposeFunction<T1, T2, TResult>(string name, Func<T1, T2, TResult> callback)
448    {
449        this.Page.ExposeFunction<T1, T2, TResult>(name, callback);
450    }
451
452    protected virtual void ExposeFunction<T1, T2, T3, TResult>(string name, Func<T1, T2, T3, TResult> callback)
453    {
454        this.Page.ExposeFunction<T1, T2, T3, TResult>(name, callback);
455    }
456
457    protected virtual void ExposeFunction<T1, T2, T3, T4, TResult>(string name, Func<T1, T2, T3, T4, TResult> callback)
458    {
459        this.Page.ExposeFunction<T1, T2, T3, T4, TResult>(name, callback);
460    }
461
462    protected virtual string? GetAttribute(string selector, string name, PageWaitForSelectorOptions? waitOptions = null, PageGetAttributeOptions? queryOptions = null)
463    {
464        this.Page.WaitForSelector(selector, waitOptions);
465        return this.Page.GetAttribute(selector, name, queryOptions);
466    }
467
468    protected virtual string InnerHTML(string selector, PageWaitForSelectorOptions? waitOptions = null, PageInnerHTMLOptions? queryOptions = null)
469    {
470        this.Page.WaitForSelector(selector, waitOptions);
471        return this.Page.InnerHTML(selector, queryOptions);
472    }
473
474    protected virtual string InnerText(string selector, PageInnerTextOptions? queryOptions = null)
475    {
476        return this.Page.InnerText(selector, queryOptions);
477    }
478
479    protected virtual string InputValue(string selector, PageInputValueOptions? queryOptions = null)
480    {
481        return this.Page.InputValue(selector, queryOptions);
482    }
483
484    protected virtual bool IsChecked(string selector, PageIsCheckedOptions? queryOptions = null)
485    {
486        return this.Page.IsChecked(selector, queryOptions);
487    }
488
489    protected virtual bool IsDisabled(string selector, PageIsDisabledOptions? options = null)
490    {
491        return this.Page.IsDisabled(selector, options);
492    }
493
494    protected virtual bool IsEditable(string selector, PageIsEditableOptions? options = null)
495    {
496        return this.Page.IsEditable(selector, options);
497    }
498
499    protected virtual bool IsEnabled(string selector, PageIsEnabledOptions? options = null)
500    {
501        return this.Page.IsEnabled(selector, options);
502    }
503
504    protected virtual bool IsHidden(string selector, PageIsHiddenOptions? options = null)
505    {
506        return this.Page.IsHidden(selector, options);
507    }
508
509    protected virtual bool IsVisible(string selector, PageIsVisibleOptions? options = null)
510    {
511        return this.Page.IsVisible(selector, options);
512    }
513
514    protected virtual ILocator IsVisible(string selector)
515    {
516        return this.Page.Locator(selector);
517    }
518
519    protected virtual void Route(string url, Action<IRoute> handler, PageRouteOptions? options = null)
520    {
521        this.Page.Route(url, handler, options);
522    }
523
524    protected virtual void Route(Regex url, Action<IRoute> handler, PageRouteOptions? options = null)
525    {
526        this.Page.Route(url, handler, options);
527    }
528
529    protected virtual void Route(Func<string, bool> url, Action<IRoute> handler, PageRouteOptions? options = null)
530    {
531        this.Page.Route(url, handler, options);
532    }
533
534    protected virtual void Unroute(string url, Action<IRoute>? handler = null)
535    {
536        this.Page.Unroute(url, handler);
537    }
538
539    protected virtual void Unroute(Regex url, Action<IRoute>? handler = null)
540    {
541        this.Page.Unroute(url, handler);
542    }
543
544    protected virtual void Unroute(Func<string, bool> url, Action<IRoute>? handler = null)
545    {
546        this.Page.Unroute(url, handler);
547    }
548
549    protected virtual IFrame? Frame(string name)
550    {
551        return this.Page.Frame(name);
552    }
553
554    protected virtual IFrame? FrameByUrl(string url)
555    {
556        return this.Page.FrameByUrl(url);
557    }
558
559    protected virtual IFrame? FrameByUrl(Regex url)
560    {
561        return this.Page.FrameByUrl(url);
562    }
563
564    protected virtual IFrame? FrameyUrl(Func<string, bool> url)
565    {
566        return this.Page.FrameByUrl(url);
567    }
568
569    protected virtual IConsoleMessage RunAndWaitForConsoleMessage(Func<Task> action, PageRunAndWaitForConsoleMessageOptions? options = null)
570    {
571        return this.Page.RunAndWaitForConsoleMessage(action, options);
572    }
573
574    protected virtual IDownload RunAndWaitForDownload(Func<Task> action, PageRunAndWaitForDownloadOptions? options = null)
575    {
576        return this.Page.RunAndWaitForDownload(action, options);
577    }
578
579    protected virtual IFileChooser RunAndWaitForFileChooser(Func<Task> action, PageRunAndWaitForFileChooserOptions? options = null)
580    {
581        return this.Page.RunAndWaitForFileChooser(action, options);
582    }
583
584    protected virtual IResponse? RunAndWaitForNavigation(Func<Task> action, PageRunAndWaitForNavigationOptions? options = null)
585    {
586        return this.Page.RunAndWaitForNavigation(action, options);
587    }
588
589    protected virtual IPage RunAndWaitForPopup(Func<Task> action, PageRunAndWaitForPopupOptions? options = null)
590    {
591        return this.Page.RunAndWaitForPopup(action, options);
592    }
593
594    protected virtual IRequest RunAndWaitForRequest(Func<Task> action, string urlOrPredicate, PageRunAndWaitForRequestOptions? options = null)
595    {
596        return this.Page.RunAndWaitForRequest(action, urlOrPredicate, options);
597    }
598
599    protected virtual IRequest RunAndWaitForRequest(Func<Task> action, Regex urlOrPredicate, PageRunAndWaitForRequestOptions? options = null)
600    {
601        return this.Page.RunAndWaitForRequest(action, urlOrPredicate, options);
602    }
603
604    protected virtual IRequest RunAndWaitForRequest(Func<Task> action, Func<IRequest, bool> urlOrPredicate, PageRunAndWaitForRequestOptions? options = null)
605    {
606        return this.Page.RunAndWaitForRequest(action, urlOrPredicate, options);
607    }
608
609    protected virtual IRequest RunAndWaitForRequestFinished(Func<Task> action, PageRunAndWaitForRequestFinishedOptions? options = null)
610    {
611        return this.Page.RunAndWaitForRequestFinished(action, options);
612    }
613
614    protected virtual IResponse RunAndWaitForResponse(Func<Task> action, string urlOrPredicate, PageRunAndWaitForResponseOptions? options = null)
615    {
616        return this.Page.RunAndWaitForResponse(action, urlOrPredicate, options);
617    }
618
619    protected virtual IResponse RunAndWaitForResponse(Func<Task> action, Regex urlOrPredicate, PageRunAndWaitForResponseOptions? options = null)
620    {
621        return this.Page.RunAndWaitForResponse(action, urlOrPredicate, options);
622    }
623
624    protected virtual IWebSocket RunAndWaitForWebSocket(Func<Task> action, PageRunAndWaitForWebSocketOptions? options = null)
625    {
626        return this.Page.RunAndWaitForWebSocket(action, options);
627    }
628
629    protected virtual void RunAndWaitForWorker(Func<Task> action, PageRunAndWaitForWorkerOptions? options = null)
630    {
631        this.Page.RunAndWaitForWorker(action, options);
632    }
633
634    protected virtual void Screenshot(PageScreenshotOptions? options = null)
635    {
636        this.Page.Screenshot(options);
637    }
638
639    protected virtual byte[] Pdf(PagePdfOptions? options = null)
640    {
641        return this.Page.Pdf(options);
642    }
643
644    protected virtual void SetContent(string html, PageSetContentOptions? options = null)
645    {
646        this.Page.SetContent(html, options);
647    }
648
649    protected virtual void SetExtraHTTPHeaders(IEnumerable<KeyValuePair<string, string>> headers)
650    {
651        this.Page.SetExtraHTTPHeaders(headers);
652    }
653
654    protected virtual void SetViewportSize(int width, int height)
655    {
656        this.Page.SetViewportSize(width, height);
657    }
658
659    protected virtual string? TextContent(string selector, PageTextContentOptions? options = null)
660    {
661        return this.Page.TextContent(selector, options);
662    }
663
664    protected virtual string Title()
665    {
666        return this.Page.Title();
667    }
668
669    protected virtual IConsoleMessage WaitForConsoleMessage(PageWaitForConsoleMessageOptions? options = null)
670    {
671        return this.Page.WaitForConsoleMessage(options);
672    }
673
674    protected virtual IDownload WaitForDownload(PageWaitForDownloadOptions? options = null)
675    {
676        return this.Page.WaitForDownload(options);
677    }
678
679    protected virtual IFileChooser WaitForFileChooser(PageWaitForFileChooserOptions? options = null)
680    {
681        return this.Page.WaitForFileChooser(options);
682    }
683
684    protected virtual IJSHandle WaitForFunction(string expression, object? arg = null, PageWaitForFunctionOptions? options = null)
685    {
686        return this.Page.WaitForFunction(expression, arg, options);
687    }
688
689    protected virtual void WaitForLoadState(LoadState? state = null, PageWaitForLoadStateOptions? options = null)
690    {
691        this.Page.WaitForLoadState(state, options);
692    }
693
694    protected virtual IResponse? WaitForNavigation(PageWaitForNavigationOptions? options = null)
695    {
696        return this.Page.WaitForNavigation(options);
697    }
698
699    protected virtual IPage WaitForPopup(PageWaitForPopupOptions? options = null)
700    {
701        return this.Page.WaitForPopup(options);
702    }
703
704    protected virtual IRequest WaitForRequest(string urlOrPredicate, PageWaitForRequestOptions? options = null)
705    {
706        return this.Page.WaitForRequest(urlOrPredicate, options);
707    }
708
709    protected virtual IRequest WaitForRequest(Regex urlOrPredicate, PageWaitForRequestOptions? options = null)
710    {
711        return this.Page.WaitForRequest(urlOrPredicate, options);
712    }
713
714    protected virtual IRequest WaitForRequest(Func<IRequest, bool> urlOrPredicate, PageWaitForRequestOptions? options = null)
715    {
716        return this.Page.WaitForRequest(urlOrPredicate, options);
717    }
718
719    protected virtual IRequest WaitForRequestFinished(PageWaitForRequestFinishedOptions? options = null)
720    {
721        return this.Page.WaitForRequestFinished(options);
722    }
723
724    protected virtual IResponse WaitForResponse(string urlOrPredicate, PageWaitForResponseOptions? options = null)
725    {
726        return this.Page.WaitForResponse(urlOrPredicate, options);
727    }
728
729    protected virtual IResponse WaitForResponse(Regex urlOrPredicate, PageWaitForResponseOptions? options = null)
730    {
731        return this.Page.WaitForResponse(urlOrPredicate, options);
732    }
733
734    protected virtual IResponse WaitForResponse(Func<IResponse, bool> urlOrPredicate, PageWaitForResponseOptions? options = null)
735    {
736        return this.Page.WaitForResponse(urlOrPredicate, options);
737    }
738
739    protected virtual IResponse RunAndWaitForResponse(Func<Task> action, Func<IResponse, bool> urlOrPredicate, PageRunAndWaitForResponseOptions? options = null)
740    {
741        return this.Page.RunAndWaitForResponse(action, urlOrPredicate, options);
742    }
743
744    protected virtual IElementHandle? WaitForSelector(string selector, PageWaitForSelectorOptions? options = null)
745    {
746        return this.Page.WaitForSelector(selector, options);
747    }
748
749    protected virtual void WaitForTimeout(float timeout)
750    {
751        this.Page.WaitForTimeout(timeout);
752    }
753
754    protected virtual void WaitForURL(Regex url, PageWaitForURLOptions? options = null)
755    {
756        this.Page.WaitForURL(url, options);
757    }
758
759    protected virtual void WaitForURL(Func<string, bool> url, PageWaitForURLOptions? options = null)
760    {
761        this.Page.WaitForURL(url, options);
762    }
763
764    protected virtual IWebSocket WaitForWebSocket(PageWaitForWebSocketOptions? options = null)
765    {
766        return this.Page.WaitForWebSocket(options);
767    }
768
769    protected virtual IWorker WaitForWorker(PageWaitForWorkerOptions? options = null)
770    {
771        return this.Page.WaitForWorker(options);
772    }
773
774    protected virtual IPage? Opener()
775    {
776        return this.Page.Opener();
777    }
778
779    protected virtual void Pause()
780    {
781        this.Page.Pause();
782    }
783
784    protected string GetComputedStyle(
785        string selector,
786        string styleName,
787        PageWaitForSelectorOptions? waitOptions = null,
788        PageQuerySelectorOptions? queryOptions = null)
789    {
790        var element = this.GetElement(selector, waitOptions, queryOptions);
791        var styleValue = this.Page.Evaluate<string>($"e => getComputedStyle(e).{styleName}", element);
792        return styleValue;
793    }
794}
795
Full Screen

Page.cs

Source: Page.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) 2020 Darío Kondratiuk
5 * Copyright (c) 2020 Meir Blachman
6 * Modifications copyright (c) Microsoft Corporation.
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in all
16 * copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 * SOFTWARE.
25 */
26using System;
27using System.Collections.Generic;
28using System.Data.SqlTypes;
29using System.IO;
30using System.Linq;
31using System.Text.Json;
32using System.Text.RegularExpressions;
33using System.Threading.Tasks;
34using Microsoft.Playwright.Helpers;
35using Microsoft.Playwright.Transport;
36using Microsoft.Playwright.Transport.Channels;
37using Microsoft.Playwright.Transport.Protocol;
38
39namespace Microsoft.Playwright.Core
40{
41    internal partial class Page : ChannelOwnerBase, IChannelOwner<Page>, IPage
42    {
43        private readonly PageChannel _channel;
44        private readonly List<Frame> _frames = new();
45        private readonly List<(IEvent PageEvent, TaskCompletionSource<bool> WaitTcs)> _waitForCancellationTcs = new();
46        private readonly object _fileChooserEventLock = new();
47        private readonly IAccessibility _accessibility;
48        private readonly IMouse _mouse;
49        private readonly IKeyboard _keyboard;
50        private readonly ITouchscreen _touchscreen;
51        private readonly PageInitializer _initializer;
52
53        private List<RouteSetting> _routes = new();
54        private EventHandler<IFileChooser> _fileChooserEventHandler;
55        private bool _fileChooserIntercepted;
56        private Video _video;
57        private float _defaultNavigationTimeout;
58        private float _defaultTimeout;
59
60        internal Page(IChannelOwner parent, string guid, PageInitializer initializer) : base(parent, guid)
61        {
62            Context = (BrowserContext)parent;
63
64            _channel = new(guid, parent.Connection, this);
65
66            MainFrame = initializer.MainFrame;
67            MainFrame.Page = this;
68            _frames.Add(MainFrame);
69            if (initializer.ViewportSize != null)
70            {
71                ViewportSize = new() { Width = initializer.ViewportSize.Width, Height = initializer.ViewportSize.Height };
72            }
73
74            IsClosed = initializer.IsClosed;
75            _accessibility = new Accessibility(_channel);
76            _keyboard = new Keyboard(_channel);
77            _touchscreen = new Touchscreen(_channel);
78            _mouse = new Mouse(_channel);
79            _channel.Closed += (_, _) => OnClose();
80            _channel.Crashed += Channel_Crashed;
81            _channel.Popup += (_, e) => Popup?.Invoke(this, e.Page);
82            _channel.WebSocket += (_, e) => WebSocket?.Invoke(this, e);
83            _channel.BindingCall += Channel_BindingCall;
84            _channel.Route += (_, e) => OnRoute(e.Route, e.Request);
85            _channel.FrameAttached += Channel_FrameAttached;
86            _channel.FrameDetached += Channel_FrameDetached;
87            _channel.Dialog += (_, e) =>
88            {
89                if (Dialog == null)
90                {
91                    if ("beforeunload".Equals(e.Type, StringComparison.Ordinal))
92                    {
93                        e.AcceptAsync(null).IgnoreException();
94                    }
95                    else
96                    {
97                        e.DismissAsync().IgnoreException();
98                    }
99                }
100                else
101                {
102                    Dialog?.Invoke(this, e);
103                }
104            };
105            _channel.Console += (_, e) => Console?.Invoke(this, e);
106            _channel.DOMContentLoaded += (_, _) => DOMContentLoaded?.Invoke(this, this);
107            _channel.Download += (_, e) => Download?.Invoke(this, new Download(this, e.Url, e.SuggestedFilename, e.Artifact.Object));
108            _channel.PageError += (_, e) => PageError?.Invoke(this, e.ToString());
109            _channel.Load += (_, _) => Load?.Invoke(this, this);
110            _channel.Video += (_, e) => ForceVideo().ArtifactReady(e.Artifact);
111
112            _channel.FileChooser += (_, e) => _fileChooserEventHandler?.Invoke(this, new FileChooser(this, e.Element.Object, e.IsMultiple));
113            _channel.Worker += (_, e) =>
114            {
115                WorkersList.Add(e.WorkerChannel.Object);
116                e.WorkerChannel.Object.Page = this;
117                Worker?.Invoke(this, e.WorkerChannel.Object);
118            };
119
120            _defaultNavigationTimeout = Context.DefaultNavigationTimeout;
121            _defaultTimeout = Context.DefaultTimeout;
122            _initializer = initializer;
123
124            Close += (_, _) => ClosedOrCrashedTcs.TrySetResult(true);
125            Crash += (_, _) => ClosedOrCrashedTcs.TrySetResult(true);
126        }
127
128        public event EventHandler<IConsoleMessage> Console;
129
130        public event EventHandler<IPage> Popup;
131
132        public event EventHandler<IRequest> Request;
133
134        public event EventHandler<IWebSocket> WebSocket;
135
136        public event EventHandler<IResponse> Response;
137
138        public event EventHandler<IRequest> RequestFinished;
139
140        public event EventHandler<IRequest> RequestFailed;
141
142        public event EventHandler<IDialog> Dialog;
143
144        public event EventHandler<IFrame> FrameAttached;
145
146        public event EventHandler<IFrame> FrameDetached;
147
148        public event EventHandler<IFrame> FrameNavigated;
149
150        public event EventHandler<IFileChooser> FileChooser
151        {
152            add
153            {
154                lock (_fileChooserEventLock)
155                {
156                    _fileChooserEventHandler += value;
157                    _fileChooserIntercepted = true;
158                    _channel.SetFileChooserInterceptedNoReplyAsync(true).IgnoreException();
159                }
160            }
161
162            remove
163            {
164                lock (_fileChooserEventLock)
165                {
166                    _fileChooserEventHandler -= value;
167
168                    if (_fileChooserIntercepted)
169                    {
170                        _fileChooserIntercepted = false;
171                        _channel.SetFileChooserInterceptedNoReplyAsync(false).IgnoreException();
172                    }
173                }
174            }
175        }
176
177        public event EventHandler<IPage> Load;
178
179        public event EventHandler<IPage> DOMContentLoaded;
180
181        public event EventHandler<IPage> Close;
182
183        public event EventHandler<IPage> Crash;
184
185        public event EventHandler<string> PageError;
186
187        public event EventHandler<IWorker> Worker;
188
189        public event EventHandler<IDownload> Download;
190
191        ChannelBase IChannelOwner.Channel => _channel;
192
193        IChannel<Page> IChannelOwner<Page>.Channel => _channel;
194
195        public bool IsClosed { get; private set; }
196
197        IFrame IPage.MainFrame => MainFrame;
198
199        public Frame MainFrame { get; }
200
201        IBrowserContext IPage.Context => Context;
202
203        public BrowserContext Context { get; set; }
204
205        public PageViewportSizeResult ViewportSize { get; private set; }
206
207        public IAccessibility Accessibility
208        {
209            get => _accessibility;
210            set => throw new NotSupportedException();
211        }
212
213        public IMouse Mouse
214        {
215            get => _mouse;
216            set => throw new NotSupportedException();
217        }
218
219        public string Url => MainFrame.Url;
220
221        public IReadOnlyList<IFrame> Frames => _frames.AsReadOnly();
222
223        public IKeyboard Keyboard
224        {
225            get => _keyboard;
226        }
227
228        public ITouchscreen Touchscreen
229        {
230            get => _touchscreen;
231        }
232
233        public IReadOnlyList<IWorker> Workers => WorkersList;
234
235        public IVideo Video
236        {
237            get
238            {
239                if (Context.Options.RecordVideoDir == null)
240                {
241                    return null;
242                }
243
244                return ForceVideo();
245            }
246            set => _video = value as Video;
247        }
248
249        internal BrowserContext OwnedContext { get; set; }
250
251        internal Dictionary<string, Delegate> Bindings { get; } = new();
252
253        internal List<Worker> WorkersList { get; } = new();
254
255        internal Page Opener => _initializer.Opener;
256
257        internal PageChannel Channel => _channel;
258
259        internal float DefaultTimeout
260        {
261            get => _defaultTimeout;
262            set
263            {
264                _defaultTimeout = value;
265                _channel.SetDefaultTimeoutNoReplyAsync(value).IgnoreException();
266            }
267        }
268
269        internal float DefaultNavigationTimeout
270        {
271            get => _defaultNavigationTimeout;
272            set
273            {
274                _defaultNavigationTimeout = value;
275                _channel.SetDefaultNavigationTimeoutNoReplyAsync(value).IgnoreException();
276            }
277        }
278
279        internal TaskCompletionSource<bool> ClosedOrCrashedTcs { get; } = new();
280
281        public IFrame Frame(string name)
282            => Frames.FirstOrDefault(f => f.Name == name);
283
284        public IFrame FrameByUrl(string urlString) => Frames.FirstOrDefault(f => Context.UrlMatches(urlString, f.Url));
285
286        public IFrame FrameByUrl(Regex urlRegex) => Frames.FirstOrDefault(f => urlRegex.IsMatch(f.Url));
287
288        public IFrame FrameByUrl(Func<string, bool> urlFunc) => Frames.FirstOrDefault(f => urlFunc(f.Url));
289
290        IFrameLocator IPage.FrameLocator(string selector) => MainFrame.FrameLocator(selector);
291
292        public Task<string> TitleAsync() => MainFrame.TitleAsync();
293
294        public Task BringToFrontAsync() => _channel.BringToFrontAsync();
295
296        public Task<IPage> OpenerAsync() => Task.FromResult<IPage>(Opener?.IsClosed == false ? Opener : null);
297
298        public Task EmulateMediaAsync(PageEmulateMediaOptions options = default)
299        {
300            var args = new Dictionary<string, object>
301            {
302                ["media"] = options?.Media,
303                ["colorScheme"] = options?.ColorScheme,
304                ["reducedMotion"] = options?.ReducedMotion,
305                ["forcedColors"] = options?.ForcedColors,
306            };
307            return _channel.EmulateMediaAsync(args);
308        }
309
310        public Task<IResponse> GotoAsync(string url, PageGotoOptions options = default)
311            => MainFrame.GotoAsync(url, new() { WaitUntil = options?.WaitUntil, Timeout = options?.Timeout, Referer = options?.Referer });
312
313        public Task WaitForURLAsync(string url, PageWaitForURLOptions options = default)
314            => MainFrame.WaitForURLAsync(url, new() { WaitUntil = options?.WaitUntil, Timeout = options?.Timeout });
315
316        public Task WaitForURLAsync(Regex url, PageWaitForURLOptions options = default)
317            => MainFrame.WaitForURLAsync(url, new() { WaitUntil = options?.WaitUntil, Timeout = options?.Timeout });
318
319        public Task WaitForURLAsync(Func<string, bool> url, PageWaitForURLOptions options = default)
320            => MainFrame.WaitForURLAsync(url, new() { WaitUntil = options?.WaitUntil, Timeout = options?.Timeout });
321
322        public Task<IConsoleMessage> WaitForConsoleMessageAsync(PageWaitForConsoleMessageOptions options = default)
323            => InnerWaitForEventAsync(PageEvent.Console, null, options?.Predicate, options?.Timeout);
324
325        public Task<IFileChooser> WaitForFileChooserAsync(PageWaitForFileChooserOptions options = default)
326            => InnerWaitForEventAsync(PageEvent.FileChooser, null, options?.Predicate, options?.Timeout);
327
328        public Task<IPage> WaitForPopupAsync(PageWaitForPopupOptions options = default)
329            => InnerWaitForEventAsync(PageEvent.Popup, null, options?.Predicate, options?.Timeout);
330
331        public Task<IWebSocket> WaitForWebSocketAsync(PageWaitForWebSocketOptions options = default)
332            => InnerWaitForEventAsync(PageEvent.WebSocket, null, options?.Predicate, options?.Timeout);
333
334        public Task<IWorker> WaitForWorkerAsync(PageWaitForWorkerOptions options = default)
335            => InnerWaitForEventAsync(PageEvent.Worker, null, options?.Predicate, options?.Timeout);
336
337        public Task<IResponse> WaitForNavigationAsync(PageWaitForNavigationOptions options = default)
338            => MainFrame.WaitForNavigationAsync(new()
339            {
340                UrlString = options?.UrlString,
341                UrlRegex = options?.UrlRegex,
342                UrlFunc = options?.UrlFunc,
343                WaitUntil = options?.WaitUntil,
344                Timeout = options?.Timeout,
345            });
346
347        public Task<IResponse> RunAndWaitForNavigationAsync(Func<Task> action, PageRunAndWaitForNavigationOptions options = default)
348            => MainFrame.RunAndWaitForNavigationAsync(action, new()
349            {
350                UrlString = options?.UrlString,
351                UrlRegex = options?.UrlRegex,
352                UrlFunc = options?.UrlFunc,
353                WaitUntil = options?.WaitUntil,
354                Timeout = options?.Timeout,
355            });
356
357        public Task<IRequest> WaitForRequestAsync(string urlOrPredicate, PageWaitForRequestOptions options = default)
358            => InnerWaitForEventAsync(PageEvent.Request, null, e => Context.UrlMatches(e.Url, urlOrPredicate), options?.Timeout);
359
360        public Task<IRequest> WaitForRequestAsync(Regex urlOrPredicate, PageWaitForRequestOptions options = default)
361            => InnerWaitForEventAsync(PageEvent.Request, null, e => urlOrPredicate.IsMatch(e.Url), options?.Timeout);
362
363        public Task<IRequest> WaitForRequestAsync(Func<IRequest, bool> urlOrPredicate, PageWaitForRequestOptions options = default)
364            => InnerWaitForEventAsync(PageEvent.Request, null, e => urlOrPredicate(e), options?.Timeout);
365
366        public Task<IRequest> WaitForRequestFinishedAsync(PageWaitForRequestFinishedOptions options = default)
367            => InnerWaitForEventAsync(PageEvent.RequestFinished, null, options?.Predicate, options?.Timeout);
368
369        public Task<IResponse> WaitForResponseAsync(string urlOrPredicate, PageWaitForResponseOptions options = default)
370            => InnerWaitForEventAsync(PageEvent.Response, null, e => Context.UrlMatches(e.Url, urlOrPredicate), options?.Timeout);
371
372        public Task<IResponse> WaitForResponseAsync(Regex urlOrPredicate, PageWaitForResponseOptions options = default)
373            => InnerWaitForEventAsync(PageEvent.Response, null, e => urlOrPredicate.IsMatch(e.Url), options?.Timeout);
374
375        public Task<IResponse> WaitForResponseAsync(Func<IResponse, bool> urlOrPredicate, PageWaitForResponseOptions options = default)
376            => InnerWaitForEventAsync(PageEvent.Response, null, e => urlOrPredicate(e), options?.Timeout);
377
378        public Task<IConsoleMessage> RunAndWaitForConsoleMessageAsync(Func<Task> action, PageRunAndWaitForConsoleMessageOptions options = default)
379            => InnerWaitForEventAsync(PageEvent.Console, action, options?.Predicate, options?.Timeout);
380
381        public Task<IDownload> WaitForDownloadAsync(PageWaitForDownloadOptions options = default)
382            => InnerWaitForEventAsync(PageEvent.Download, null, options?.Predicate, options?.Timeout);
383
384        public Task<IDownload> RunAndWaitForDownloadAsync(Func<Task> action, PageRunAndWaitForDownloadOptions options = default)
385            => InnerWaitForEventAsync(PageEvent.Download, action, options?.Predicate, options?.Timeout);
386
387        public Task<IFileChooser> RunAndWaitForFileChooserAsync(Func<Task> action, PageRunAndWaitForFileChooserOptions options = default)
388            => InnerWaitForEventAsync(PageEvent.FileChooser, action, options?.Predicate, options?.Timeout);
389
390        public Task<IPage> RunAndWaitForPopupAsync(Func<Task> action, PageRunAndWaitForPopupOptions options = default)
391            => InnerWaitForEventAsync(PageEvent.Popup, action, options?.Predicate, options?.Timeout);
392
393        public Task<IRequest> RunAndWaitForRequestFinishedAsync(Func<Task> action, PageRunAndWaitForRequestFinishedOptions options = default)
394            => InnerWaitForEventAsync(PageEvent.RequestFinished, action, options?.Predicate, options?.Timeout);
395
396        public Task<IWebSocket> RunAndWaitForWebSocketAsync(Func<Task> action, PageRunAndWaitForWebSocketOptions options = default)
397            => InnerWaitForEventAsync(PageEvent.WebSocket, action, options?.Predicate, options?.Timeout);
398
399        public Task<IWorker> RunAndWaitForWorkerAsync(Func<Task> action, PageRunAndWaitForWorkerOptions options = default)
400            => InnerWaitForEventAsync(PageEvent.Worker, action, options?.Predicate, options?.Timeout);
401
402        public Task<IRequest> RunAndWaitForRequestAsync(Func<Task> action, string urlOrPredicate, PageRunAndWaitForRequestOptions options = default)
403            => InnerWaitForEventAsync(PageEvent.Request, action, e => Context.UrlMatches(e.Url, urlOrPredicate), options?.Timeout);
404
405        public Task<IRequest> RunAndWaitForRequestAsync(Func<Task> action, Regex urlOrPredicate, PageRunAndWaitForRequestOptions options = default)
406            => InnerWaitForEventAsync(PageEvent.Request, action, e => urlOrPredicate.IsMatch(e.Url), options?.Timeout);
407
408        public Task<IRequest> RunAndWaitForRequestAsync(Func<Task> action, Func<IRequest, bool> urlOrPredicate, PageRunAndWaitForRequestOptions options = default)
409            => InnerWaitForEventAsync(PageEvent.Request, action, e => urlOrPredicate(e), options?.Timeout);
410
411        public Task<IResponse> RunAndWaitForResponseAsync(Func<Task> action, string urlOrPredicate, PageRunAndWaitForResponseOptions options = default)
412            => InnerWaitForEventAsync(PageEvent.Response, action, e => Context.UrlMatches(e.Url, urlOrPredicate), options?.Timeout);
413
414        public Task<IResponse> RunAndWaitForResponseAsync(Func<Task> action, Regex urlOrPredicate, PageRunAndWaitForResponseOptions options = default)
415            => InnerWaitForEventAsync(PageEvent.Response, action, e => urlOrPredicate.IsMatch(e.Url), options?.Timeout);
416
417        public Task<IResponse> RunAndWaitForResponseAsync(Func<Task> action, Func<IResponse, bool> urlOrPredicate, PageRunAndWaitForResponseOptions options = default)
418            => InnerWaitForEventAsync(PageEvent.Response, action, e => urlOrPredicate(e), options?.Timeout);
419
420        public Task<IJSHandle> WaitForFunctionAsync(string expression, object arg = default, PageWaitForFunctionOptions options = default)
421            => MainFrame.WaitForFunctionAsync(expression, arg, new() { PollingInterval = options?.PollingInterval, Timeout = options?.Timeout });
422
423        public async Task<T> InnerWaitForEventAsync<T>(PlaywrightEvent<T> pageEvent, Func<Task> action = default, Func<T, bool> predicate = default, float? timeout = default)
424        {
425            if (pageEvent == null)
426            {
427                throw new ArgumentException("Page event is required", nameof(pageEvent));
428            }
429
430            timeout ??= _defaultTimeout;
431            using var waiter = new Waiter(this, $"page.WaitForEventAsync(\"{typeof(T)}\")");
432            waiter.RejectOnTimeout(Convert.ToInt32(timeout), $"Timeout {timeout}ms exceeded while waiting for event \"{pageEvent.Name}\"");
433
434            if (pageEvent.Name != PageEvent.Crash.Name)
435            {
436                waiter.RejectOnEvent<IPage>(this, PageEvent.Crash.Name, new("Page crashed"));
437            }
438
439            if (pageEvent.Name != PageEvent.Close.Name)
440            {
441                waiter.RejectOnEvent<IPage>(this, PageEvent.Close.Name, new("Page closed"));
442            }
443
444            var result = waiter.WaitForEventAsync(this, pageEvent.Name, predicate);
445            if (action != null)
446            {
447                await WrapApiBoundaryAsync(() => Task.WhenAll(result, action())).ConfigureAwait(false);
448            }
449
450            return await result.ConfigureAwait(false);
451        }
452
453        public async Task CloseAsync(PageCloseOptions options = default)
454        {
455            try
456            {
457                await _channel.CloseAsync(options?.RunBeforeUnload ?? false).ConfigureAwait(false);
458                if (OwnedContext != null)
459                {
460                    await OwnedContext.CloseAsync().ConfigureAwait(false);
461                }
462            }
463            catch (Exception e) when (DriverMessages.IsSafeCloseError(e))
464            {
465                // Swallow exception
466            }
467        }
468
469        public Task<T> EvaluateAsync<T>(string expression, object arg) => MainFrame.EvaluateAsync<T>(expression, arg);
470
471        public Task<JsonElement?> EvalOnSelectorAsync(string selector, string expression, object arg) => MainFrame.EvalOnSelectorAsync(selector, expression, arg);
472
473        public Task<T> EvalOnSelectorAsync<T>(string selector, string expression, object arg = null, PageEvalOnSelectorOptions options = null)
474            => MainFrame.EvalOnSelectorAsync<T>(selector, expression, arg, new() { Strict = options?.Strict });
475
476        public ILocator Locator(string selector, PageLocatorOptions options = default)
477            => MainFrame.Locator(selector, new() { HasTextString = options?.HasTextString, HasTextRegex = options?.HasTextRegex, Has = options?.Has });
478
479        public Task<IElementHandle> QuerySelectorAsync(string selector, PageQuerySelectorOptions options = null)
480            => MainFrame.QuerySelectorAsync(selector, new() { Strict = options?.Strict });
481
482        public Task<T> EvalOnSelectorAsync<T>(string selector, string expression, object arg) => MainFrame.EvalOnSelectorAsync<T>(selector, expression, arg);
483
484        public Task<JsonElement?> EvalOnSelectorAllAsync(string selector, string expression, object arg) => MainFrame.EvalOnSelectorAllAsync(selector, expression, arg);
485
486        public Task<T> EvalOnSelectorAllAsync<T>(string selector, string expression, object arg) => MainFrame.EvalOnSelectorAllAsync<T>(selector, expression, arg);
487
488        public Task FillAsync(string selector, string value, PageFillOptions options = default)
489            => MainFrame.FillAsync(selector, value, new() { NoWaitAfter = options?.NoWaitAfter, Timeout = options?.Timeout, Force = options?.Force, Strict = options?.Strict });
490
491        public Task SetInputFilesAsync(string selector, string files, PageSetInputFilesOptions options = default)
492            => MainFrame.SetInputFilesAsync(selector, files, Map(options));
493
494        public Task SetInputFilesAsync(string selector, IEnumerable<string> files, PageSetInputFilesOptions options = default)
495            => MainFrame.SetInputFilesAsync(selector, files, Map(options));
496
497        public Task SetInputFilesAsync(string selector, FilePayload files, PageSetInputFilesOptions options = default)
498            => MainFrame.SetInputFilesAsync(selector, files, Map(options));
499
500        public Task SetInputFilesAsync(string selector, IEnumerable<FilePayload> files, PageSetInputFilesOptions options = default)
501            => MainFrame.SetInputFilesAsync(selector, files, Map(options));
502
503        public Task TypeAsync(string selector, string text, PageTypeOptions options = default)
504            => MainFrame.TypeAsync(selector, text, new()
505            {
506                Delay = options?.Delay,
507                NoWaitAfter = options?.NoWaitAfter,
508                Timeout = options?.Timeout,
509                Strict = options?.Strict,
510            });
511
512        public Task FocusAsync(string selector, PageFocusOptions options = default)
513            => MainFrame.FocusAsync(selector, new()
514            {
515                Timeout = options?.Timeout,
516                Strict = options?.Strict,
517            });
518
519        public Task HoverAsync(string selector, PageHoverOptions options = default)
520            => MainFrame.HoverAsync(
521                selector,
522                new()
523                {
524                    Position = options?.Position,
525                    Modifiers = options?.Modifiers,
526                    Force = options?.Force,
527                    Timeout = options?.Timeout,
528                    Trial = options?.Trial,
529                    Strict = options?.Strict,
530                });
531
532        public Task PressAsync(string selector, string key, PagePressOptions options = default)
533            => MainFrame.PressAsync(selector, key, new()
534            {
535                Delay = options?.Delay,
536                NoWaitAfter = options?.NoWaitAfter,
537                Timeout = options?.Timeout,
538                Strict = options?.Strict,
539            });
540
541        public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, string values, PageSelectOptionOptions options = default)
542            => SelectOptionAsync(selector, new[] { values }, options);
543
544        public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<string> values, PageSelectOptionOptions options = default)
545            => SelectOptionAsync(selector, values.Select(x => new SelectOptionValue() { Value = x }), options);
546
547        public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IElementHandle values, PageSelectOptionOptions options = default)
548            => SelectOptionAsync(selector, new[] { values }, options);
549
550        public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<IElementHandle> values, PageSelectOptionOptions options = default)
551            => MainFrame.SelectOptionAsync(selector, values, new()
552            {
553                NoWaitAfter = options?.NoWaitAfter,
554                Timeout = options?.Timeout,
555                Force = options?.Force,
556                Strict = options?.Strict,
557            });
558
559        public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, SelectOptionValue values, PageSelectOptionOptions options = default)
560            => SelectOptionAsync(selector, new[] { values }, options);
561
562        public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<SelectOptionValue> values, PageSelectOptionOptions options = default)
563            => MainFrame.SelectOptionAsync(selector, values, new()
564            {
565                NoWaitAfter = options?.NoWaitAfter,
566                Timeout = options?.Timeout,
567                Force = options?.Force,
568                Strict = options?.Strict,
569            });
570
571        public Task WaitForTimeoutAsync(float timeout) => MainFrame.WaitForTimeoutAsync(timeout);
572
573        public Task<IElementHandle> WaitForSelectorAsync(string selector, PageWaitForSelectorOptions options = default)
574            => MainFrame.WaitForSelectorAsync(selector, new()
575            {
576                State = options?.State,
577                Timeout = options?.Timeout,
578                Strict = options?.Strict,
579            });
580
581        public Task<JsonElement?> EvaluateAsync(string expression, object arg) => MainFrame.EvaluateAsync(expression, arg);
582
583        public async Task<byte[]> ScreenshotAsync(PageScreenshotOptions options = default)
584        {
585            options ??= new PageScreenshotOptions();
586            if (options.Type == null && !string.IsNullOrEmpty(options.Path))
587            {
588                options.Type = ElementHandle.DetermineScreenshotType(options.Path);
589            }
590
591            byte[] result = await _channel.ScreenshotAsync(
592                path: options.Path,
593                fullPage: options.FullPage,
594                clip: options.Clip,
595                omitBackground: options.OmitBackground,
596                type: options.Type,
597                quality: options.Quality,
598                mask: options.Mask,
599                animations: options.Animations,
600                caret: options.Caret,
601                scale: options.Scale,
602                timeout: options.Timeout).ConfigureAwait(false);
603
604            if (!string.IsNullOrEmpty(options.Path))
605            {
606                Directory.CreateDirectory(new FileInfo(options.Path).Directory.FullName);
607                File.WriteAllBytes(options.Path, result);
608            }
609
610            return result;
611        }
612
613        public Task SetContentAsync(string html, PageSetContentOptions options = default)
614            => MainFrame.SetContentAsync(html, new() { WaitUntil = options?.WaitUntil, Timeout = options?.Timeout });
615
616        public Task<string> ContentAsync() => MainFrame.ContentAsync();
617
618        public Task SetExtraHTTPHeadersAsync(IEnumerable<KeyValuePair<string, string>> headers)
619            => _channel.SetExtraHTTPHeadersAsync(headers);
620
621        public Task<IElementHandle> QuerySelectorAsync(string selector) => MainFrame.QuerySelectorAsync(selector);
622
623        public Task<IReadOnlyList<IElementHandle>> QuerySelectorAllAsync(string selector)
624            => MainFrame.QuerySelectorAllAsync(selector);
625
626        public Task<IJSHandle> EvaluateHandleAsync(string expression, object arg) => MainFrame.EvaluateHandleAsync(expression, arg);
627
628        public Task<IElementHandle> AddScriptTagAsync(PageAddScriptTagOptions options = default)
629            => MainFrame.AddScriptTagAsync(new()
630            {
631                Url = options?.Url,
632                Path = options?.Path,
633                Content = options?.Content,
634                Type = options?.Type,
635            });
636
637        public Task<IElementHandle> AddStyleTagAsync(PageAddStyleTagOptions options = default)
638            => MainFrame.AddStyleTagAsync(new()
639            {
640                Url = options?.Url,
641                Path = options?.Path,
642                Content = options?.Content,
643            });
644
645        public Task ClickAsync(string selector, PageClickOptions options = default)
646            => MainFrame.ClickAsync(
647                selector,
648                new()
649                {
650                    Button = options?.Button,
651                    ClickCount = options?.ClickCount,
652                    Delay = options?.Delay,
653                    Position = options?.Position,
654                    Modifiers = options?.Modifiers,
655                    Force = options?.Force,
656                    NoWaitAfter = options?.NoWaitAfter,
657                    Timeout = options?.Timeout,
658                    Trial = options?.Trial,
659                    Strict = options?.Strict,
660                });
661
662        public Task DblClickAsync(string selector, PageDblClickOptions options = default)
663            => MainFrame.DblClickAsync(selector, new()
664            {
665                Delay = options?.Delay,
666                Button = options?.Button,
667                Position = options?.Position,
668                Modifiers = options?.Modifiers,
669                Timeout = options?.Timeout,
670                Force = options?.Force,
671                NoWaitAfter = options?.NoWaitAfter,
672                Trial = options?.Trial,
673                Strict = options?.Strict,
674            });
675
676        public async Task<IResponse> GoBackAsync(PageGoBackOptions options = default)
677            => (await _channel.GoBackAsync(options?.Timeout, options?.WaitUntil).ConfigureAwait(false))?.Object;
678
679        public async Task<IResponse> GoForwardAsync(PageGoForwardOptions options = default)
680            => (await _channel.GoForwardAsync(options?.Timeout, options?.WaitUntil).ConfigureAwait(false))?.Object;
681
682        public async Task<IResponse> ReloadAsync(PageReloadOptions options = default)
683            => (await _channel.ReloadAsync(options?.Timeout, options?.WaitUntil).ConfigureAwait(false))?.Object;
684
685        public Task ExposeBindingAsync(string name, Action callback, PageExposeBindingOptions options = default)
686            => InnerExposeBindingAsync(name, (Delegate)callback, options?.Handle ?? false);
687
688        public Task ExposeBindingAsync(string name, Action<BindingSource> callback)
689            => InnerExposeBindingAsync(name, (Delegate)callback);
690
691        public Task ExposeBindingAsync<T>(string name, Action<BindingSource, T> callback)
692            => InnerExposeBindingAsync(name, (Delegate)callback);
693
694        public Task ExposeBindingAsync<TResult>(string name, Func<BindingSource, TResult> callback)
695            => InnerExposeBindingAsync(name, (Delegate)callback);
696
697        public Task ExposeBindingAsync<TResult>(string name, Func<BindingSource, IJSHandle, TResult> callback)
698            => InnerExposeBindingAsync(name, (Delegate)callback, true);
699
700        public Task ExposeBindingAsync<T, TResult>(string name, Func<BindingSource, T, TResult> callback)
701            => InnerExposeBindingAsync(name, (Delegate)callback);
702
703        public Task ExposeBindingAsync<T1, T2, TResult>(string name, Func<BindingSource, T1, T2, TResult> callback)
704            => InnerExposeBindingAsync(name, (Delegate)callback);
705
706        public Task ExposeBindingAsync<T1, T2, T3, TResult>(string name, Func<BindingSource, T1, T2, T3, TResult> callback)
707            => InnerExposeBindingAsync(name, (Delegate)callback);
708
709        public Task ExposeBindingAsync<T1, T2, T3, T4, TResult>(string name, Func<BindingSource, T1, T2, T3, T4, TResult> callback)
710            => InnerExposeBindingAsync(name, (Delegate)callback);
711
712        public Task ExposeFunctionAsync(string name, Action callback)
713            => ExposeBindingAsync(name, (BindingSource _) => callback());
714
715        public Task ExposeFunctionAsync<T>(string name, Action<T> callback)
716            => ExposeBindingAsync(name, (BindingSource _, T t) => callback(t));
717
718        public Task ExposeFunctionAsync<TResult>(string name, Func<TResult> callback)
719            => ExposeBindingAsync(name, (BindingSource _) => callback());
720
721        public Task ExposeFunctionAsync<T, TResult>(string name, Func<T, TResult> callback)
722            => ExposeBindingAsync(name, (BindingSource _, T t) => callback(t));
723
724        public Task ExposeFunctionAsync<T1, T2, TResult>(string name, Func<T1, T2, TResult> callback)
725            => ExposeBindingAsync(name, (BindingSource _, T1 t1, T2 t2) => callback(t1, t2));
726
727        public Task ExposeFunctionAsync<T1, T2, T3, TResult>(string name, Func<T1, T2, T3, TResult> callback)
728            => ExposeBindingAsync(name, (BindingSource _, T1 t1, T2 t2, T3 t3) => callback(t1, t2, t3));
729
730        public Task ExposeFunctionAsync<T1, T2, T3, T4, TResult>(string name, Func<T1, T2, T3, T4, TResult> callback)
731            => ExposeBindingAsync(name, (BindingSource _, T1 t1, T2 t2, T3 t3, T4 t4) => callback(t1, t2, t3, t4));
732
733        public async Task<byte[]> PdfAsync(PagePdfOptions options = default)
734        {
735            if (!Context.IsChromium)
736            {
737                throw new NotSupportedException("This browser doesn't support this action.");
738            }
739
740            byte[] result = await _channel.PdfAsync(
741                scale: options?.Scale,
742                displayHeaderFooter: options?.DisplayHeaderFooter,
743                headerTemplate: options?.HeaderTemplate,
744                footerTemplate: options?.FooterTemplate,
745                printBackground: options?.PrintBackground,
746                landscape: options?.Landscape,
747                pageRanges: options?.PageRanges,
748                format: options?.Format,
749                width: options?.Width,
750                height: options?.Height,
751                margin: options?.Margin,
752                preferCSSPageSize: options?.PreferCSSPageSize).ConfigureAwait(false);
753
754            if (!string.IsNullOrEmpty(options?.Path))
755            {
756                Directory.CreateDirectory(new FileInfo(options.Path).Directory.FullName);
757                File.WriteAllBytes(options.Path, result);
758            }
759
760            return result;
761        }
762
763        public Task AddInitScriptAsync(string script, string scriptPath)
764            => _channel.AddInitScriptAsync(ScriptsHelper.EvaluationScript(script, scriptPath));
765
766        public Task RouteAsync(string url, Action<IRoute> handler, PageRouteOptions options = null)
767            => RouteAsync(new Regex(Context.CombineUrlWithBase(url).GlobToRegex()), null, handler, options);
768
769        public Task RouteAsync(Regex url, Action<IRoute> handler, PageRouteOptions options = null)
770             => RouteAsync(url, null, handler, options);
771
772        public Task RouteAsync(Func<string, bool> url, Action<IRoute> handler, PageRouteOptions options = null)
773            => RouteAsync(null, url, handler, options);
774
775        public Task UnrouteAsync(string urlString, Action<IRoute> handler)
776            => UnrouteAsync(new Regex(Context.CombineUrlWithBase(urlString).GlobToRegex()), null, handler);
777
778        public Task UnrouteAsync(Regex urlString, Action<IRoute> handler)
779            => UnrouteAsync(urlString, null, handler);
780
781        public Task UnrouteAsync(Func<string, bool> urlFunc, Action<IRoute> handler)
782            => UnrouteAsync(null, urlFunc, handler);
783
784        public Task WaitForLoadStateAsync(LoadState? state = default, PageWaitForLoadStateOptions options = default)
785            => MainFrame.WaitForLoadStateAsync(state, new() { Timeout = options?.Timeout });
786
787        public Task SetViewportSizeAsync(int width, int height)
788        {
789            ViewportSize = new() { Width = width, Height = height };
790            return _channel.SetViewportSizeAsync(ViewportSize);
791        }
792
793        public Task SetCheckedAsync(string selector, bool checkedState, PageSetCheckedOptions options = null)
794            => checkedState ?
795            MainFrame.CheckAsync(selector, new()
796            {
797                Position = options?.Position,
798                Force = options?.Force,
799                NoWaitAfter = options?.NoWaitAfter,
800                Strict = options?.Strict,
801                Timeout = options?.Timeout,
802                Trial = options?.Trial,
803            })
804            : MainFrame.UncheckAsync(selector, new()
805            {
806                Position = options?.Position,
807                Force = options?.Force,
808                NoWaitAfter = options?.NoWaitAfter,
809                Timeout = options?.Timeout,
810                Trial = options?.Trial,
811                Strict = options?.Strict,
812            });
813
814        public Task CheckAsync(string selector, PageCheckOptions options = default)
815            => MainFrame.CheckAsync(selector, new()
816            {
817                Position = options?.Position,
818                Force = options?.Force,
819                NoWaitAfter = options?.NoWaitAfter,
820                Strict = options?.Strict,
821                Timeout = options?.Timeout,
822                Trial = options?.Trial,
823            });
824
825        public Task UncheckAsync(string selector, PageUncheckOptions options = default)
826            => MainFrame.UncheckAsync(selector, new()
827            {
828                Position = options?.Position,
829                Force = options?.Force,
830                NoWaitAfter = options?.NoWaitAfter,
831                Timeout = options?.Timeout,
832                Trial = options?.Trial,
833                Strict = options?.Strict,
834            });
835
836        public Task DispatchEventAsync(string selector, string type, object eventInit = default, PageDispatchEventOptions options = default)
837             => MainFrame.DispatchEventAsync(selector, type, eventInit, new() { Timeout = options?.Timeout, Strict = options?.Strict });
838
839        public Task<string> GetAttributeAsync(string selector, string name, PageGetAttributeOptions options = default)
840             => MainFrame.GetAttributeAsync(selector, name, new()
841             {
842                 Timeout = options?.Timeout,
843                 Strict = options?.Strict,
844             });
845
846        public Task<string> InnerHTMLAsync(string selector, PageInnerHTMLOptions options = default)
847             => MainFrame.InnerHTMLAsync(selector, new()
848             {
849                 Timeout = options?.Timeout,
850                 Strict = options?.Strict,
851             });
852
853        public Task<string> InnerTextAsync(string selector, PageInnerTextOptions options = default)
854             => MainFrame.InnerTextAsync(selector, new()
855             {
856                 Timeout = options?.Timeout,
857                 Strict = options?.Strict,
858             });
859
860        public Task<string> TextContentAsync(string selector, PageTextContentOptions options = default)
861             => MainFrame.TextContentAsync(selector, new()
862             {
863                 Timeout = options?.Timeout,
864                 Strict = options?.Strict,
865             });
866
867        public Task TapAsync(string selector, PageTapOptions options = default)
868            => MainFrame.TapAsync(
869                selector,
870                new()
871                {
872                    Modifiers = options?.Modifiers,
873                    Position = options?.Position,
874                    Force = options?.Force,
875                    NoWaitAfter = options?.NoWaitAfter,
876                    Timeout = options?.Timeout,
877                    Trial = options?.Trial,
878                    Strict = options?.Strict,
879                });
880
881        public Task<bool> IsCheckedAsync(string selector, PageIsCheckedOptions options = default)
882            => MainFrame.IsCheckedAsync(selector, new()
883            {
884                Timeout = options?.Timeout,
885                Strict = options?.Strict,
886            });
887
888        public Task<bool> IsDisabledAsync(string selector, PageIsDisabledOptions options = default)
889            => MainFrame.IsDisabledAsync(selector, new()
890            {
891                Timeout = options?.Timeout,
892                Strict = options?.Strict,
893            });
894
895        public Task<bool> IsEditableAsync(string selector, PageIsEditableOptions options = default)
896            => MainFrame.IsEditableAsync(selector, new()
897            {
898                Timeout = options?.Timeout,
899                Strict = options?.Strict,
900            });
901
902        public Task<bool> IsEnabledAsync(string selector, PageIsEnabledOptions options = default)
903            => MainFrame.IsEnabledAsync(selector, new()
904            {
905                Timeout = options?.Timeout,
906                Strict = options?.Strict,
907            });
908
909#pragma warning disable CS0612 // Type or member is obsolete
910        public Task<bool> IsHiddenAsync(string selector, PageIsHiddenOptions options = default)
911            => MainFrame.IsHiddenAsync(selector, new()
912            {
913                Timeout = options?.Timeout,
914                Strict = options?.Strict,
915            });
916
917        public Task<bool> IsVisibleAsync(string selector, PageIsVisibleOptions options = default)
918            => MainFrame.IsVisibleAsync(selector, new()
919            {
920                Timeout = options?.Timeout,
921                Strict = options?.Strict,
922            });
923#pragma warning restore CS0612 // Type or member is obsolete
924
925        public Task PauseAsync() => Context.Channel.PauseAsync();
926
927        public void SetDefaultNavigationTimeout(float timeout) => DefaultNavigationTimeout = timeout;
928
929        public void SetDefaultTimeout(float timeout) => DefaultTimeout = timeout;
930
931        public Task<string> InputValueAsync(string selector, PageInputValueOptions options = null)
932            => MainFrame.InputValueAsync(selector, new()
933            {
934                Timeout = options?.Timeout,
935                Strict = options?.Strict,
936            });
937
938        public Task DragAndDropAsync(string source, string target, PageDragAndDropOptions options = null)
939            => MainFrame.DragAndDropAsync(source, target, new()
940            {
941                Force = options?.Force,
942                NoWaitAfter = options?.NoWaitAfter,
943                Timeout = options?.Timeout,
944                Trial = options?.Trial,
945                Strict = options?.Strict,
946            });
947
948        internal void NotifyPopup(Page page) => Popup?.Invoke(this, page);
949
950        internal void OnFrameNavigated(Frame frame)
951            => FrameNavigated?.Invoke(this, frame);
952
953        internal void FireRequest(IRequest request) => Request?.Invoke(this, request);
954
955        internal void FireRequestFailed(IRequest request) => RequestFailed?.Invoke(this, request);
956
957        internal void FireRequestFinished(IRequest request) => RequestFinished?.Invoke(this, request);
958
959        internal void FireResponse(IResponse response) => Response?.Invoke(this, response);
960
961        private Task RouteAsync(Regex urlRegex, Func<string, bool> urlFunc, Action<IRoute> handler, PageRouteOptions options)
962            => RouteAsync(new()
963            {
964                Regex = urlRegex,
965                Function = urlFunc,
966                Handler = handler,
967                Times = options?.Times,
968            });
969
970        private Task RouteAsync(RouteSetting setting)
971        {
972            _routes.Insert(0, setting);
973
974            if (_routes.Count == 1)
975            {
976                return _channel.SetNetworkInterceptionEnabledAsync(true);
977            }
978
979            return Task.CompletedTask;
980        }
981
982        private Task UnrouteAsync(Regex urlRegex, Func<string, bool> urlFunc, Action<IRoute> handler = null)
983            => UnrouteAsync(new()
984            {
985                Function = urlFunc,
986                Regex = urlRegex,
987                Handler = handler,
988            });
989
990        private Task UnrouteAsync(RouteSetting setting)
991        {
992            var newRoutesList = new List<RouteSetting>();
993            newRoutesList.AddRange(_routes.Where(r =>
994                (setting.Regex != null && !(r.Regex == setting.Regex || (r.Regex.ToString() == setting.Regex.ToString() && r.Regex.Options == setting.Regex.Options))) ||
995                (setting.Function != null && r.Function != setting.Function) ||
996                (setting.Handler != null && r.Handler != setting.Handler)));
997            _routes = newRoutesList;
998
999            if (_routes.Count == 0)
1000            {
1001                return DisableInterceptionAsync();
1002            }
1003
1004            return Task.CompletedTask;
1005        }
1006
1007        internal void OnClose()
1008        {
1009            IsClosed = true;
1010            Context?.PagesList.Remove(this);
1011            RejectPendingOperations(false);
1012            Close?.Invoke(this, this);
1013        }
1014
1015        private void Channel_Crashed(object sender, EventArgs e)
1016        {
1017            RejectPendingOperations(true);
1018            Crash?.Invoke(this, this);
1019        }
1020
1021        private void Channel_BindingCall(object sender, BindingCallEventArgs e)
1022        {
1023            if (Bindings.TryGetValue(e.BindingCall.Name, out var binding))
1024            {
1025                _ = e.BindingCall.CallAsync(binding);
1026            }
1027        }
1028
1029        private void OnRoute(Route route, IRequest request)
1030        {
1031            foreach (var routeHandler in _routes.ToList())
1032            {
1033                if ((routeHandler.Regex?.IsMatch(request.Url) == true) ||
1034                    (routeHandler.Function?.Invoke(request.Url) == true))
1035                {
1036                    try
1037                    {
1038                        routeHandler.Handle(route);
1039                    }
1040                    finally
1041                    {
1042                        if (!routeHandler.IsActive())
1043                        {
1044                            _routes.Remove(routeHandler);
1045                            if (_routes.Count == 0)
1046                            {
1047                                DisableInterceptionAsync().ConfigureAwait(false);
1048                            }
1049                        }
1050                    }
1051                    return;
1052                }
1053            }
1054
1055            Context.OnRoute(route, request);
1056        }
1057
1058        internal async Task DisableInterceptionAsync()
1059        {
1060            await Channel.SetNetworkInterceptionEnabledAsync(false).ConfigureAwait(false);
1061        }
1062
1063        private void Channel_FrameDetached(object sender, IFrame args)
1064        {
1065            var frame = (Frame)args;
1066            _frames.Remove(frame);
1067            frame.IsDetached = true;
1068            frame.ParentFrame?.ChildFramesList?.Remove(frame);
1069            FrameDetached?.Invoke(this, args);
1070        }
1071
1072        private void Channel_FrameAttached(object sender, IFrame args)
1073        {
1074            var frame = (Frame)args;
1075            frame.Page = this;
1076            _frames.Add(frame);
1077            frame.ParentFrame?.ChildFramesList?.Add(frame);
1078            FrameAttached?.Invoke(this, args);
1079        }
1080
1081        private void RejectPendingOperations(bool isCrash)
1082        {
1083            foreach (var (_, waitTcs) in _waitForCancellationTcs.Where(e => e.PageEvent != (isCrash ? PageEvent.Crash : PageEvent.Close)))
1084            {
1085                waitTcs.TrySetException(new PlaywrightException(isCrash ? "Page crashed" : "Page closed"));
1086            }
1087
1088            _waitForCancellationTcs.Clear();
1089        }
1090
1091        private Task InnerExposeBindingAsync(string name, Delegate callback, bool handle = false)
1092        {
1093            if (Bindings.ContainsKey(name))
1094            {
1095                throw new PlaywrightException($"Function \"{name}\" has been already registered");
1096            }
1097
1098            Bindings.Add(name, callback);
1099
1100            return _channel.ExposeBindingAsync(name, handle);
1101        }
1102
1103        private Video ForceVideo() => _video ??= new(this, _channel.Connection);
1104
1105        private FrameSetInputFilesOptions Map(PageSetInputFilesOptions options)
1106        {
1107            if (options == null)
1108            {
1109                return null;
1110            }
1111
1112            return new()
1113            {
1114                NoWaitAfter = options.NoWaitAfter,
1115                Timeout = options.Timeout,
1116                Strict = options.Strict,
1117            };
1118        }
1119    }
1120}
1121
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

Most used method in PageWaitForPopupOptions

Trigger PageWaitForPopupOptions code on LambdaTest Cloud Grid

Execute automation tests with PageWaitForPopupOptions on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
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)