How to use BindingSource class of Microsoft.Playwright package

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

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

BrowserContextExposeFunctionTests.cs

Source: BrowserContextExposeFunctionTests.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.Collections.Generic;
26using System.Text.Json;
27using System.Threading.Tasks;
28using Microsoft.Playwright.NUnit;
29using NUnit.Framework;
30
31namespace Microsoft.Playwright.Tests
32{
33    public class BrowserContextExposeFunctionTests : ContextTestEx
34    {
35        [PlaywrightTest("browsercontext-expose-function.spec.ts", "expose binding should work")]
36        public async Task ExposeBindingShouldWork()
37        {
38            BindingSource bindingSource = null;
39
40            await Context.ExposeBindingAsync("add", (BindingSource source, int a, int b) =>
41            {
42                bindingSource = source;
43                return a + b;
44            });
45
46            var page = await Context.NewPageAsync();
47            int result = await page.EvaluateAsync<int>(@"async function() {
48                return await add(5, 6);
49            }");
50
51            Assert.AreEqual(Context, bindingSource.Context);
52            Assert.AreEqual(page, bindingSource.Page);
53            Assert.AreEqual(page.MainFrame, bindingSource.Frame);
54
55            Assert.AreEqual(11, result);
56        }
57
58        [PlaywrightTest("browsercontext-expose-function.spec.ts", "should work")]
59        public async Task ShouldWork()
60        {
61            await Context.ExposeFunctionAsync("add", (int a, int b) => a + b);
62            var page = await Context.NewPageAsync();
63
64            await page.ExposeFunctionAsync("mul", (int a, int b) => a * b);
65            await Context.ExposeFunctionAsync("sub", (int a, int b) => a - b);
66
67            var result = await page.EvaluateAsync<JsonElement>(@"async function() {
68                return { mul: await mul(9, 4), add: await add(9, 4), sub: await sub(9, 4) };
69            }");
70            Assert.AreEqual(36, result.GetProperty("mul").GetInt32());
71            Assert.AreEqual(13, result.GetProperty("add").GetInt32());
72            Assert.AreEqual(5, result.GetProperty("sub").GetInt32());
73        }
74
75        [PlaywrightTest("browsercontext-expose-function.spec.ts", "should throw for duplicate registrations")]
76        public async Task ShouldThrowForDuplicateRegistrations()
77        {
78            await Context.ExposeFunctionAsync("foo", () => { });
79            await Context.ExposeFunctionAsync("bar", () => { });
80
81            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Context.ExposeFunctionAsync("foo", () => { }));
82            Assert.AreEqual("Function \"foo\" has been already registered", exception.Message);
83
84            var page = await Context.NewPageAsync();
85            exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.ExposeFunctionAsync("foo", () => { }));
86            Assert.AreEqual("Function \"foo\" has been already registered in the browser context", exception.Message);
87
88            await page.ExposeFunctionAsync("baz", () => { });
89            exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Context.ExposeFunctionAsync("baz", () => { }));
90            Assert.AreEqual("Function \"baz\" has been already registered in one of the pages", exception.Message);
91        }
92
93        [PlaywrightTest("browsercontext-expose-function.spec.ts", "should be callable from-inside addInitScript")]
94        public async Task ShouldBeCallableFromInsideAddInitScript()
95        {
96            var args = new List<object>();
97            await using var context = await Browser.NewContextAsync();
98            await context.ExposeFunctionAsync("woof", (string arg) => { args.Add(arg); });
99
100            await context.AddInitScriptAsync("woof('context')");
101            var page = await context.NewPageAsync();
102            await page.AddInitScriptAsync("woof('page')");
103
104            args.Clear();
105            await page.ReloadAsync();
106            CollectionAssert.Contains(args, "context");
107            CollectionAssert.Contains(args, "page");
108        }
109
110        [PlaywrightTest("browsercontext-expose-function.spec.ts", "exposeBindingHandle should work")]
111        public async Task ExposeBindingHandleShouldWork()
112        {
113            IJSHandle target = null;
114            await Context.ExposeBindingAsync(
115                "logme",
116                (BindingSource _, IJSHandle t) =>
117                {
118                    target = t;
119                    return 17;
120                });
121
122            var page = await Context.NewPageAsync();
123            int result = await page.EvaluateAsync<int>(@"async function() {
124                return window['logme']({ foo: 42 });
125            }");
126
127            Assert.AreEqual(42, await target.EvaluateAsync<int>("x => x.foo"));
128            Assert.AreEqual(17, result);
129        }
130
131        public async Task ExposeBindingHandleLikeInDocumentation()
132        {
133            var result = new TaskCompletionSource<string>();
134            var page = await Context.NewPageAsync();
135            await Context.ExposeBindingAsync("clicked", async (BindingSource _, IJSHandle t) =>
136            {
137                return result.TrySetResult(await t.AsElement().TextContentAsync());
138            });
139
140            await page.SetContentAsync("<script>\n" +
141             "  document.addEventListener('click', event => window.clicked(event.target));\n" +
142             "</script>\n" +
143             "<div>Click me</div>\n" +
144             "<div>Or click me</div>\n");
145
146            await page.ClickAsync("div");
147            Assert.AreEqual("Click me", await result.Task);
148        }
149    }
150}
151
Full Screen

PageExposeFunctionTests.cs

Source: PageExposeFunctionTests.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.Linq;
26using System.Text.Json;
27using System.Threading.Tasks;
28using Microsoft.Playwright.NUnit;
29using NUnit.Framework;
30
31namespace Microsoft.Playwright.Tests
32{
33    ///<playwright-file>page-expose-function.spec.ts</playwright-file>
34    public class PageExposeFunctionTests : PageTestEx
35    {
36        [PlaywrightTest("page-expose-function.spec.ts", "exposeBinding should work")]
37        public async Task ExposeBindingShouldWork()
38        {
39            BindingSource bindingSource = null;
40
41            await Page.ExposeBindingAsync("add", (BindingSource source, int a, int b) =>
42            {
43                bindingSource = source;
44                return a + b;
45            });
46
47            int result = await Page.EvaluateAsync<int>("async function () { return add(5, 6); }");
48
49            Assert.AreEqual(Context, bindingSource.Context);
50            Assert.AreEqual(Page, bindingSource.Page);
51            Assert.AreEqual(Page.MainFrame, bindingSource.Frame);
52            Assert.AreEqual(11, result);
53        }
54
55        [PlaywrightTest("page-expose-function.spec.ts", "should work")]
56        public async Task ShouldWork()
57        {
58            await Page.ExposeFunctionAsync("compute", (int a, int b) => a * b);
59            int result = await Page.EvaluateAsync<int>(@"async function() {
60                return await compute(9, 4);
61            }");
62            Assert.AreEqual(36, result);
63        }
64
65        [PlaywrightTest("page-expose-function.spec.ts", "should work with handles and complex objects")]
66        public async Task ShouldWorkWithHandlesAndComplexObjects()
67        {
68            var fooHandle = await Page.EvaluateHandleAsync(@"() => {
69                window['fooValue'] = { bar: 2 };
70                return window['fooValue'];
71            }");
72
73            await Page.ExposeFunctionAsync("handle", () => new[] { new { foo = fooHandle } });
74
75            Assert.True(await Page.EvaluateAsync<bool>(@"async function() {
76                const value = await window['handle']();
77                const [{ foo }] = value;
78                return foo === window['fooValue'];
79            }"));
80        }
81
82        [PlaywrightTest("page-expose-function.spec.ts", "should throw exception in page context")]
83        public async Task ShouldThrowExceptionInPageContext()
84        {
85            await Page.ExposeFunctionAsync("woof", (System.Action)(() =>
86            {
87                throw new PlaywrightException("WOOF WOOF");
88            }));
89            var result = await Page.EvaluateAsync<JsonElement>(@"async () => {
90                try
91                {
92                    await woof();
93                }
94                catch (e)
95                {
96                    return { message: e.message, stack: e.stack};
97                }
98            }");
99            Assert.AreEqual("WOOF WOOF", result.GetProperty("message").GetString());
100            StringAssert.Contains(nameof(PageExposeFunctionTests), result.GetProperty("stack").GetString());
101        }
102
103        [PlaywrightTest("page-expose-function.spec.ts", @"should support throwing ""null""")]
104        public async Task ShouldSupportThrowingNull()
105        {
106            await Page.ExposeFunctionAsync("woof", () =>
107            {
108                throw null;
109            });
110            var result = await Page.EvaluateAsync(@"async () => {
111                try {
112                    await window['woof']();
113                } catch (e) {
114                    return e;
115                }
116            }");
117            Assert.AreEqual(null, null);
118        }
119
120        [PlaywrightTest("page-expose-function.spec.ts", "should be callable from-inside addInitScript")]
121        public async Task ShouldBeCallableFromInsideAddInitScript()
122        {
123            bool called = false;
124            await Page.ExposeFunctionAsync("woof", () =>
125            {
126                called = true;
127            });
128            await Page.AddInitScriptAsync("woof()");
129            await Page.ReloadAsync();
130            Assert.True(called);
131        }
132
133        [PlaywrightTest("page-expose-function.spec.ts", "should survive navigation")]
134        public async Task ShouldSurviveNavigation()
135        {
136            await Page.ExposeFunctionAsync("compute", (int a, int b) => a * b);
137            await Page.GotoAsync(Server.EmptyPage);
138            int result = await Page.EvaluateAsync<int>(@"async function() {
139                return await compute(9, 4);
140            }");
141            Assert.AreEqual(36, result);
142        }
143
144        [PlaywrightTest("page-expose-function.spec.ts", "should await returned promise")]
145        public async Task ShouldAwaitReturnedPromise()
146        {
147            await Page.ExposeFunctionAsync("compute", (int a, int b) => Task.FromResult(a * b));
148            int result = await Page.EvaluateAsync<int>(@"async function() {
149                return await compute(3, 5);
150            }");
151            Assert.AreEqual(15, result);
152        }
153
154        [PlaywrightTest("page-expose-function.spec.ts", "should work on frames")]
155        public async Task ShouldWorkOnFrames()
156        {
157            await Page.ExposeFunctionAsync("compute", (int a, int b) => Task.FromResult(a * b));
158            await Page.GotoAsync(Server.Prefix + "/frames/nested-frames.html");
159            var frame = Page.Frames.ElementAt(1);
160            int result = await frame.EvaluateAsync<int>(@"async function() {
161                return await compute(3, 5);
162            }");
163            Assert.AreEqual(15, result);
164        }
165
166        [PlaywrightTest("page-expose-function.spec.ts", "should work on frames before navigation")]
167        public async Task ShouldWorkOnFramesBeforeNavigation()
168        {
169            await Page.GotoAsync(Server.Prefix + "/frames/nested-frames.html");
170            await Page.ExposeFunctionAsync("compute", (int a, int b) => Task.FromResult(a * b));
171            var frame = Page.Frames.ElementAt(1);
172            int result = await frame.EvaluateAsync<int>(@"async function() {
173                return await compute(3, 5);
174            }");
175            Assert.AreEqual(15, result);
176        }
177
178        [PlaywrightTest("page-expose-function.spec.ts", "should work after cross origin navigation")]
179        public async Task ShouldWorkAfterCrossOriginNavigation()
180        {
181            await Page.GotoAsync(Server.EmptyPage);
182            await Page.ExposeFunctionAsync("compute", (int a, int b) => a * b);
183            await Page.GotoAsync(Server.CrossProcessPrefix + "/empty.html");
184            int result = await Page.EvaluateAsync<int>(@"async function() {
185                return await compute(9, 4);
186            }");
187            Assert.AreEqual(36, result);
188        }
189
190        [PlaywrightTest("page-expose-function.spec.ts", "should work with complex objects")]
191        public async Task ShouldWorkWithComplexObjects()
192        {
193            await Page.ExposeFunctionAsync("complexObject", (ComplexObject a, ComplexObject b) =>
194            {
195                return new ComplexObject { x = a.x + b.x };
196            });
197            var result = await Page.EvaluateAsync<ComplexObject>("async () => complexObject({ x: 5}, { x: 2})");
198            Assert.AreEqual(7, result.x);
199        }
200
201        [PlaywrightTest("page-expose-function.spec.ts", "exposeBindingHandle should work")]
202        public async Task ExposeBindingHandleShouldWork()
203        {
204            IJSHandle target = null;
205            await Page.ExposeBindingAsync(
206                "logme",
207                (_, t) =>
208                {
209                    target = t;
210                    return 17;
211                });
212
213            int result = await Page.EvaluateAsync<int>(@"async function() {
214                return window['logme']({ foo: 42 });
215            }");
216
217            Assert.AreEqual(42, await target.EvaluateAsync<int>("x => x.foo"));
218            Assert.AreEqual(17, result);
219        }
220
221        [PlaywrightTest("page-expose-function.spec.ts", "exposeBindingHandle should not throw during navigation")]
222        public async Task ExposeBindingHandleShouldNotThrowDuringNavigation()
223        {
224            IJSHandle target = null;
225            await Page.ExposeBindingAsync(
226                "logme",
227                (_, t) =>
228                {
229                    target = t;
230                    return 17;
231                });
232
233            await TaskUtils.WhenAll(
234                Page.WaitForNavigationAsync(new() { WaitUntil = WaitUntilState.Load }),
235                Page.EvaluateAsync(@"async url => {
236                    window['logme']({ foo: 42 });
237                    window.location.href = url;
238                }", Server.Prefix + "/one-style.html"));
239        }
240
241        [PlaywrightTest("browsercontext-expose-function.spec.ts", "should throw for duplicate registrations")]
242        public async Task ShouldThrowForDuplicateRegistrations()
243        {
244            await Page.ExposeFunctionAsync("foo", () => { });
245            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.ExposeFunctionAsync("foo", () => { }));
246            Assert.AreEqual("Function \"foo\" has been already registered", exception.Message);
247        }
248
249        [PlaywrightTest]
250        public async Task ShouldReturnNullForTask()
251        {
252            await Page.ExposeFunctionAsync("compute", () => Task.CompletedTask);
253            await Page.GotoAsync(Server.EmptyPage);
254            var result = await Page.EvaluateAsync(@"async function() {
255                return await compute();
256            }");
257            Assert.IsNull(result);
258        }
259
260        [PlaywrightTest]
261        public async Task ShouldReturnNullForTaskDelay()
262        {
263            await Page.ExposeFunctionAsync("compute", () => Task.Delay(100));
264            await Page.GotoAsync(Server.EmptyPage);
265            var result = await Page.EvaluateAsync(@"async function() {
266                return await compute();
267            }");
268            Assert.IsNull(result);
269        }
270
271        internal class ComplexObject
272        {
273            public int x { get; set; }
274        }
275    }
276}
277
Full Screen

BrowserContextSynchronous.cs

Source: BrowserContextSynchronous.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) Evgeny Nazarchuk.
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 System.Text.RegularExpressions;
27
28namespace Playwright.Synchronous;
29
30public static class BrowserContextSynchronous
31{
32    /// <summary>
33    /// <para>
34    /// Adds cookies into this browser context. All pages within this context will have
35    /// these cookies installed. Cookies can be obtained via <see cref="IBrowserContext.CookiesAsync"/>.
36    /// </para>
37    /// <code>await context.AddCookiesAsync(new[] { cookie1, cookie2 });</code>
38    /// </summary>
39    /// <param name="cookies">
40    /// </param>
41    public static IBrowserContext AddCookies(this IBrowserContext browserContext, IEnumerable<Cookie> cookies)
42    {
43        browserContext.AddCookiesAsync(cookies).GetAwaiter().GetResult();
44        return browserContext;
45    }
46
47    /// <summary>
48    /// <para>Adds a script which would be evaluated in one of the following scenarios:</para>
49    /// <list type="bullet">
50    /// <item><description>Whenever a page is created in the browser context or is navigated.</description></item>
51    /// <item><description>
52    /// Whenever a child frame is attached or navigated in any page in the browser context.
53    /// In this case, the script is evaluated in the context of the newly attached frame.
54    /// </description></item>
55    /// </list>
56    /// <para>
57    /// The script is evaluated after the document was created but before any of its scripts
58    /// were run. This is useful to amend the JavaScript environment, e.g. to seed <c>Math.random</c>.
59    /// </para>
60    /// <para>An example of overriding <c>Math.random</c> before the page loads:</para>
61    /// <code>await context.AddInitScriptAsync(new BrowserContextAddInitScriptOptions { ScriptPath = "preload.js" });</code>
62    /// </summary>
63    /// <remarks>
64    /// <para>
65    /// The order of evaluation of multiple scripts installed via <see cref="IBrowserContext.AddInitScriptAsync"/>
66    /// and <see cref="IPage.AddInitScriptAsync"/> is not defined.
67    /// </para>
68    /// </remarks>
69    /// <param name="script">Script to be evaluated in all pages in the browser context.</param>
70    /// <param name="scriptPath">Instead of specifying <paramref name="script"/>, gives the file name to load from.</param>
71    public static IBrowserContext AddInitScript(this IBrowserContext browserContext, string? script = null, string? scriptPath = null)
72    {
73        browserContext.AddInitScriptAsync(script, scriptPath).GetAwaiter().GetResult();
74        return browserContext;
75    }
76
77    /// <summary><para>Clears context cookies.</para></summary>
78    public static IBrowserContext ClearCookies(this IBrowserContext browserContext)
79    {
80        browserContext.ClearCookiesAsync().GetAwaiter().GetResult();
81        return browserContext;
82    }
83
84    /// <summary>
85    /// <para>Clears all permission overrides for the browser context.</para>
86    /// <code>
87    /// var context = await browser.NewContextAsync();<br/>
88    /// await context.GrantPermissionsAsync(new[] { "clipboard-read" });<br/>
89    /// // Alternatively, you can use the helper class ContextPermissions<br/>
90    /// //  to specify the permissions...<br/>
91    /// // do stuff ...<br/>
92    /// await context.ClearPermissionsAsync();
93    /// </code>
94    /// </summary>
95    public static IBrowserContext ClearPermissions(this IBrowserContext browserContext)
96    {
97        browserContext.ClearPermissionsAsync().GetAwaiter().GetResult();
98        return browserContext;
99    }
100
101    /// <summary>
102    /// <para>
103    /// Closes the browser context. All the pages that belong to the browser context will
104    /// be closed.
105    /// </para>
106    /// </summary>
107    /// <remarks><para>The default browser context cannot be closed.</para></remarks>
108    public static IBrowserContext Close(this IBrowserContext browserContext)
109    {
110        browserContext.CloseAsync().GetAwaiter().GetResult();
111        return browserContext;
112    }
113
114    /// <summary>
115    /// <para>
116    /// If no URLs are specified, this method returns all cookies. If URLs are specified,
117    /// only cookies that affect those URLs are returned.
118    /// </para>
119    /// </summary>
120    /// <param name="urls">Optional list of URLs.</param>
121    public static IReadOnlyList<BrowserContextCookiesResult> Cookies(this IBrowserContext browserContext, IEnumerable<string>? urls = null)
122    {
123        return browserContext.CookiesAsync(urls).GetAwaiter().GetResult();
124    }
125
126    /// <summary>
127    /// <para>
128    /// The method adds a function called <paramref name="name"/> on the <c>window</c> object
129    /// of every frame in every page in the context. When called, the function executes
130    /// <paramref name="callback"/> and returns a <see cref="Task"/> which resolves to the
131    /// return value of <paramref name="callback"/>. If the <paramref name="callback"/>
132    /// returns a <see cref="Promise"/>, it will be awaited.
133    /// </para>
134    /// <para>
135    /// The first argument of the <paramref name="callback"/> function contains information
136    /// about the caller: <c>{ browserContext: BrowserContext, page: Page, frame: Frame
137    /// }</c>.
138    /// </para>
139    /// <para>See <see cref="IPage.ExposeBindingAsync"/> for page-only version.</para>
140    /// <para>An example of exposing page URL to all frames in all pages in the context:</para>
141    /// <code>
142    /// using Microsoft.Playwright;<br/>
143    /// using System.Threading.Tasks;<br/>
144    /// <br/>
145    /// class Program<br/>
146    /// {<br/>
147    ///     public static async Task Main()<br/>
148    ///     {<br/>
149    ///         using var playwright = await Playwright.CreateAsync();<br/>
150    ///         var browser = await playwright.Webkit.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false });<br/>
151    ///         var context = await browser.NewContextAsync();<br/>
152    /// <br/>
153    ///         await context.ExposeBindingAsync("pageURL", source =&gt; source.Page.Url);<br/>
154    ///         var page = await context.NewPageAsync();<br/>
155    ///         await page.SetContentAsync("&lt;script&gt;\n" +<br/>
156    ///         "  async function onClick() {\n" +<br/>
157    ///         "    document.querySelector('div').textContent = await window.pageURL();\n" +<br/>
158    ///         "  }\n" +<br/>
159    ///         "&lt;/script&gt;\n" +<br/>
160    ///         "&lt;button onclick=\"onClick()\"&gt;Click me&lt;/button&gt;\n" +<br/>
161    ///         "&lt;div&gt;&lt;/div&gt;");<br/>
162    ///         await page.ClickAsync("button");<br/>
163    ///     }<br/>
164    /// }
165    /// </code>
166    /// <para>An example of passing an element handle:</para>
167    /// <code>
168    /// var result = new TaskCompletionSource&lt;string&gt;();<br/>
169    /// var page = await Context.NewPageAsync();<br/>
170    /// await Context.ExposeBindingAsync("clicked", async (BindingSource _, IJSHandle t) =&gt;<br/>
171    /// {<br/>
172    ///     return result.TrySetResult(await t.AsElement().TextContentAsync());<br/>
173    /// });<br/>
174    /// <br/>
175    /// await page.SetContentAsync("&lt;script&gt;\n" +<br/>
176    ///   "  document.addEventListener('click', event =&gt; window.clicked(event.target));\n" +<br/>
177    ///   "&lt;/script&gt;\n" +<br/>
178    ///   "&lt;div&gt;Click me&lt;/div&gt;\n" +<br/>
179    ///   "&lt;div&gt;Or click me&lt;/div&gt;\n");<br/>
180    /// <br/>
181    /// await page.ClickAsync("div");<br/>
182    /// // Note: it makes sense to await the result here, because otherwise, the context<br/>
183    /// //  gets closed and the binding function will throw an exception.<br/>
184    /// Assert.AreEqual("Click me", await result.Task);
185    /// </code>
186    /// </summary>
187    /// <param name="name">Name of the function on the window object.</param>
188    /// <param name="callback">Callback function that will be called in the Playwright's context.</param>
189    /// <param name="options">Call options</param>
190    public static IBrowserContext ExposeBinding(this IBrowserContext browserContext, string name, Action callback, BrowserContextExposeBindingOptions? options = null)
191    {
192        browserContext.ExposeBindingAsync(name, callback, options).GetAwaiter().GetResult();
193        return browserContext;
194    }
195
196    /// <inheritdoc cref="ExposeBindingAsync(string, Action, BrowserContextExposeBindingOptions)"/>
197    public static IBrowserContext ExposeBinding(this IBrowserContext browserContext, string name, Action<BindingSource> callback)
198    {
199        browserContext.ExposeBindingAsync(name, callback).GetAwaiter().GetResult();
200        return browserContext;
201    }
202
203    /// <inheritdoc cref="ExposeBindingAsync(string, Action, BrowserContextExposeBindingOptions)"/>
204    public static IBrowserContext ExposeBinding<T>(this IBrowserContext browserContext, string name, Action<BindingSource, T> callback)
205    {
206        browserContext.ExposeBindingAsync<T>(name, callback).GetAwaiter().GetResult();
207        return browserContext;
208    }
209
210    /// <inheritdoc cref="ExposeBindingAsync(string, Action, BrowserContextExposeBindingOptions)"/>
211    public static IBrowserContext ExposeBinding<TResult>(this IBrowserContext browserContext, string name, Func<BindingSource, TResult> callback)
212    {
213        browserContext.ExposeBindingAsync<TResult>(name, callback).GetAwaiter().GetResult();
214        return browserContext;
215    }
216
217    /// <inheritdoc cref="ExposeBindingAsync(string, Action, BrowserContextExposeBindingOptions)"/>
218    public static IBrowserContext ExposeBinding<TResult>(this IBrowserContext browserContext, string name, Func<BindingSource, IJSHandle, TResult> callback)
219    {
220        browserContext.ExposeBindingAsync<TResult>(name, callback).GetAwaiter().GetResult();
221        return browserContext;
222    }
223
224    /// <inheritdoc cref="ExposeBindingAsync(string, Action, BrowserContextExposeBindingOptions)"/>
225    public static IBrowserContext ExposeBinding<T, TResult>(this IBrowserContext browserContext, string name, Func<BindingSource, T, TResult> callback)
226    {
227        browserContext.ExposeBindingAsync<T, TResult>(name, callback).GetAwaiter().GetResult();
228        return browserContext;
229    }
230
231    /// <inheritdoc cref="ExposeBindingAsync(string, Action, BrowserContextExposeBindingOptions)"/>
232    public static IBrowserContext ExposeBinding<T1, T2, TResult>(this IBrowserContext browserContext, string name, Func<BindingSource, T1, T2, TResult> callback)
233    {
234        browserContext.ExposeBindingAsync<T1, T2, TResult>(name, callback).GetAwaiter().GetResult();
235        return browserContext;
236    }
237
238    /// <inheritdoc cref="ExposeBindingAsync(string, Action, BrowserContextExposeBindingOptions)"/>
239    public static IBrowserContext ExposeBinding<T1, T2, T3, TResult>(this IBrowserContext browserContext, string name, Func<BindingSource, T1, T2, T3, TResult> callback)
240    {
241        browserContext.ExposeBindingAsync<T1, T2, T3, TResult>(name, callback).GetAwaiter().GetResult();
242        return browserContext;
243    }
244
245    /// <inheritdoc cref="ExposeBindingAsync(string, Action, BrowserContextExposeBindingOptions)"/>
246    public static IBrowserContext ExposeBinding<T1, T2, T3, T4, TResult>(this IBrowserContext browserContext, string name, Func<BindingSource, T1, T2, T3, T4, TResult> callback)
247    {
248        browserContext.ExposeBindingAsync<T1, T2, T3, T4, TResult>(name, callback).GetAwaiter().GetResult();
249        return browserContext;
250    }
251
252    /// <summary>
253    /// <para>
254    /// The method adds a function called <paramref name="name"/> on the <c>window</c> object
255    /// of every frame in every page in the context. When called, the function executes
256    /// <paramref name="callback"/> and returns a <see cref="Task"/> which resolves to the
257    /// return value of <paramref name="callback"/>.
258    /// </para>
259    /// <para>If the <paramref name="callback"/> returns a <see cref="Task"/>, it will be awaited.</para>
260    /// <para>See <see cref="IPage.ExposeFunctionAsync"/> for page-only version.</para>
261    /// <para>An example of adding a <c>sha256</c> function to all pages in the context:</para>
262    /// <code>
263    /// using Microsoft.Playwright;<br/>
264    /// using System;<br/>
265    /// using System.Security.Cryptography;<br/>
266    /// using System.Threading.Tasks;<br/>
267    /// <br/>
268    /// class BrowserContextExamples<br/>
269    /// {<br/>
270    ///     public static async Task Main()<br/>
271    ///     {<br/>
272    ///         using var playwright = await Playwright.CreateAsync();<br/>
273    ///         var browser = await playwright.Webkit.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false });<br/>
274    ///         var context = await browser.NewContextAsync();<br/>
275    /// <br/>
276    ///         await context.ExposeFunctionAsync("sha256", (string input) =&gt;<br/>
277    ///         {<br/>
278    ///             return Convert.ToBase64String(<br/>
279    ///                 SHA256.Create().ComputeHash(System.Text.Encoding.UTF8.GetBytes(input)));<br/>
280    ///         });<br/>
281    /// <br/>
282    ///         var page = await context.NewPageAsync();<br/>
283    ///         await page.SetContentAsync("&lt;script&gt;\n" +<br/>
284    ///         "  async function onClick() {\n" +<br/>
285    ///         "    document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');\n" +<br/>
286    ///         "  }\n" +<br/>
287    ///         "&lt;/script&gt;\n" +<br/>
288    ///         "&lt;button onclick=\"onClick()\"&gt;Click me&lt;/button&gt;\n" +<br/>
289    ///         "&lt;div&gt;&lt;/div&gt;");<br/>
290    /// <br/>
291    ///         await page.ClickAsync("button");<br/>
292    ///         Console.WriteLine(await page.TextContentAsync("div"));<br/>
293    ///     }<br/>
294    /// }
295    /// </code>
296    /// </summary>
297    /// <param name="name">Name of the function on the window object.</param>
298    /// <param name="callback">Callback function that will be called in the Playwright's context.</param>
299    public static IBrowserContext ExposeFunction(this IBrowserContext browserContext, string name, Action callback)
300    {
301        browserContext.ExposeFunctionAsync(name, callback).GetAwaiter().GetResult();
302        return browserContext;
303    }
304
305    /// <inheritdoc cref="ExposeFunctionAsync(string, Action)"/>
306    public static IBrowserContext ExposeFunction<T>(this IBrowserContext browserContext, string name, Action<T> callback)
307    {
308        browserContext.ExposeFunctionAsync<T>(name, callback).GetAwaiter().GetResult();
309        return browserContext;
310    }
311
312    /// <inheritdoc cref="ExposeFunctionAsync(string, Action)"/>
313    public static IBrowserContext ExposeFunction<TResult>(this IBrowserContext browserContext, string name, Func<TResult> callback)
314    {
315        browserContext.ExposeFunctionAsync<TResult>(name, callback).GetAwaiter().GetResult();
316        return browserContext;
317    }
318
319    /// <inheritdoc cref="ExposeFunctionAsync(string, Action)"/>
320    public static IBrowserContext ExposeFunction<T, TResult>(this IBrowserContext browserContext, string name, Func<T, TResult> callback)
321    {
322        browserContext.ExposeFunctionAsync<T, TResult>(name, callback).GetAwaiter().GetResult();
323        return browserContext;
324    }
325
326    /// <inheritdoc cref="ExposeFunctionAsync(string, Action)"/>
327    public static IBrowserContext ExposeFunction<T1, T2, TResult>(this IBrowserContext browserContext, string name, Func<T1, T2, TResult> callback)
328    {
329        browserContext.ExposeFunctionAsync<T1, T2, TResult>(name, callback).GetAwaiter().GetResult();
330        return browserContext;
331    }
332
333    /// <inheritdoc cref="ExposeFunctionAsync(string, Action)"/>
334    public static IBrowserContext ExposeFunction<T1, T2, T3, TResult>(this IBrowserContext browserContext, string name, Func<T1, T2, T3, TResult> callback)
335    {
336        browserContext.ExposeFunctionAsync<T1, T2, T3, TResult>(name, callback).GetAwaiter().GetResult();
337        return browserContext;
338    }
339
340    /// <inheritdoc cref="ExposeFunctionAsync(string, Action)"/>
341    public static IBrowserContext ExposeFunction<T1, T2, T3, T4, TResult>(this IBrowserContext browserContext, string name, Func<T1, T2, T3, T4, TResult> callback)
342    {
343        browserContext.ExposeFunctionAsync<T1, T2, T3, T4, TResult>(name, callback).GetAwaiter().GetResult();
344        return browserContext;
345    }
346
347    /// <summary>
348    /// <para>
349    /// Grants specified permissions to the browser context. Only grants corresponding permissions
350    /// to the given origin if specified.
351    /// </para>
352    /// </summary>
353    /// <param name="permissions">
354    /// A permission or an array of permissions to grant. Permissions can be one of the
355    /// following values:
356    /// <list type="bullet">
357    /// <item><description><c>'geolocation'</c></description></item>
358    /// <item><description><c>'midi'</c></description></item>
359    /// <item><description><c>'midi-sysex'</c> (system-exclusive midi)</description></item>
360    /// <item><description><c>'notifications'</c></description></item>
361    /// <item><description><c>'push'</c></description></item>
362    /// <item><description><c>'camera'</c></description></item>
363    /// <item><description><c>'microphone'</c></description></item>
364    /// <item><description><c>'background-sync'</c></description></item>
365    /// <item><description><c>'ambient-light-sensor'</c></description></item>
366    /// <item><description><c>'accelerometer'</c></description></item>
367    /// <item><description><c>'gyroscope'</c></description></item>
368    /// <item><description><c>'magnetometer'</c></description></item>
369    /// <item><description><c>'accessibility-events'</c></description></item>
370    /// <item><description><c>'clipboard-read'</c></description></item>
371    /// <item><description><c>'clipboard-write'</c></description></item>
372    /// <item><description><c>'payment-handler'</c></description></item>
373    /// </list>
374    /// </param>
375    /// <param name="options">Call options</param>
376    public static IBrowserContext GrantPermissions(this IBrowserContext browserContext, IEnumerable<string> permissions, BrowserContextGrantPermissionsOptions? options = null)
377    {
378        browserContext.GrantPermissionsAsync(permissions, options).GetAwaiter().GetResult();
379        return browserContext;
380    }
381
382    /// <summary><para>Creates a new page in the browser context.</para></summary>
383    public static IPage NewPage(this IBrowserContext browserContext)
384    {
385        return browserContext.NewPageAsync().GetAwaiter().GetResult();
386    }
387
388    /// <summary>
389    /// <para>
390    /// Routing provides the capability to modify network requests that are made by any
391    /// page in the browser context. Once route is enabled, every request matching the url
392    /// pattern will stall unless it's continued, fulfilled or aborted.
393    /// </para>
394    /// <para>An example of a naive handler that aborts all image requests:</para>
395    /// <code>
396    /// var context = await browser.NewContextAsync();<br/>
397    /// var page = await context.NewPageAsync();<br/>
398    /// await context.RouteAsync("**/*.{png,jpg,jpeg}", r =&gt; r.AbortAsync());<br/>
399    /// await page.GotoAsync("https://theverge.com");<br/>
400    /// await browser.CloseAsync();
401    /// </code>
402    /// <para>or the same snippet using a regex pattern instead:</para>
403    /// <code>
404    /// var context = await browser.NewContextAsync();<br/>
405    /// var page = await context.NewPageAsync();<br/>
406    /// await context.RouteAsync(new Regex("(\\.png$)|(\\.jpg$)"), r =&gt; r.AbortAsync());<br/>
407    /// await page.GotoAsync("https://theverge.com");<br/>
408    /// await browser.CloseAsync();
409    /// </code>
410    /// <para>
411    /// It is possible to examine the request to decide the route action. For example, mocking
412    /// all requests that contain some post data, and leaving all other requests as is:
413    /// </para>
414    /// <code>
415    /// await page.RouteAsync("/api/**", async r =&gt;<br/>
416    /// {<br/>
417    ///     if (r.Request.PostData.Contains("my-string"))<br/>
418    ///         await r.FulfillAsync(body: "mocked-data");<br/>
419    ///     else<br/>
420    ///         await r.ContinueAsync();<br/>
421    /// });
422    /// </code>
423    /// <para>
424    /// Page routes (set up with <see cref="IPage.RouteAsync"/>) take precedence over browser
425    /// context routes when request matches both handlers.
426    /// </para>
427    /// <para>To remove a route with its handler you can use <see cref="IBrowserContext.UnrouteAsync"/>.</para>
428    /// </summary>
429    /// <remarks>
430    /// <para>
431    /// <see cref="IPage.RouteAsync"/> will not intercept requests intercepted by Service
432    /// Worker. See <a href="https://github.com/microsoft/playwright/issues/1090">this</a>
433    /// issue. We recommend disabling Service Workers when using request interception. Via
434    /// <c>await context.addInitScript(() =&gt; delete window.navigator.serviceWorker);</c>
435    /// </para>
436    /// <para>Enabling routing disables http cache.</para>
437    /// </remarks>
438    /// <param name="url">
439    /// A glob pattern, regex pattern or predicate receiving <see cref="URL"/> to match
440    /// while routing. When a <paramref name="baseURL"/> via the context options was provided
441    /// and the passed URL is a path, it gets merged via the <a href="https://developer.mozilla.org/en-US/docs/Web/API/URL/URL"><c>new
442    /// URL()</c></a> constructor.
443    /// </param>
444    /// <param name="handler">handler function to route the request.</param>
445    /// <param name="options">Call options</param>
446    public static IBrowserContext Route(this IBrowserContext browserContext, string url, Action<IRoute> handler, BrowserContextRouteOptions? options = null)
447    {
448        browserContext.RouteAsync(url, handler, options).GetAwaiter().GetResult();
449        return browserContext;
450    }
451
452    /// <summary>
453    /// <para>
454    /// Routing provides the capability to modify network requests that are made by any
455    /// page in the browser context. Once route is enabled, every request matching the url
456    /// pattern will stall unless it's continued, fulfilled or aborted.
457    /// </para>
458    /// <para>An example of a naive handler that aborts all image requests:</para>
459    /// <code>
460    /// var context = await browser.NewContextAsync();<br/>
461    /// var page = await context.NewPageAsync();<br/>
462    /// await context.RouteAsync("**/*.{png,jpg,jpeg}", r =&gt; r.AbortAsync());<br/>
463    /// await page.GotoAsync("https://theverge.com");<br/>
464    /// await browser.CloseAsync();
465    /// </code>
466    /// <para>or the same snippet using a regex pattern instead:</para>
467    /// <code>
468    /// var context = await browser.NewContextAsync();<br/>
469    /// var page = await context.NewPageAsync();<br/>
470    /// await context.RouteAsync(new Regex("(\\.png$)|(\\.jpg$)"), r =&gt; r.AbortAsync());<br/>
471    /// await page.GotoAsync("https://theverge.com");<br/>
472    /// await browser.CloseAsync();
473    /// </code>
474    /// <para>
475    /// It is possible to examine the request to decide the route action. For example, mocking
476    /// all requests that contain some post data, and leaving all other requests as is:
477    /// </para>
478    /// <code>
479    /// await page.RouteAsync("/api/**", async r =&gt;<br/>
480    /// {<br/>
481    ///     if (r.Request.PostData.Contains("my-string"))<br/>
482    ///         await r.FulfillAsync(body: "mocked-data");<br/>
483    ///     else<br/>
484    ///         await r.ContinueAsync();<br/>
485    /// });
486    /// </code>
487    /// <para>
488    /// Page routes (set up with <see cref="IPage.RouteAsync"/>) take precedence over browser
489    /// context routes when request matches both handlers.
490    /// </para>
491    /// <para>To remove a route with its handler you can use <see cref="IBrowserContext.UnrouteAsync"/>.</para>
492    /// </summary>
493    /// <remarks>
494    /// <para>
495    /// <see cref="IPage.RouteAsync"/> will not intercept requests intercepted by Service
496    /// Worker. See <a href="https://github.com/microsoft/playwright/issues/1090">this</a>
497    /// issue. We recommend disabling Service Workers when using request interception. Via
498    /// <c>await context.addInitScript(() =&gt; delete window.navigator.serviceWorker);</c>
499    /// </para>
500    /// <para>Enabling routing disables http cache.</para>
501    /// </remarks>
502    /// <param name="url">
503    /// A glob pattern, regex pattern or predicate receiving <see cref="URL"/> to match
504    /// while routing. When a <paramref name="baseURL"/> via the context options was provided
505    /// and the passed URL is a path, it gets merged via the <a href="https://developer.mozilla.org/en-US/docs/Web/API/URL/URL"><c>new
506    /// URL()</c></a> constructor.
507    /// </param>
508    /// <param name="handler">handler function to route the request.</param>
509    /// <param name="options">Call options</param>
510    public static IBrowserContext Route(this IBrowserContext browserContext, Regex url, Action<IRoute> handler, BrowserContextRouteOptions? options = null)
511    {
512        browserContext.RouteAsync(url, handler, options).GetAwaiter().GetResult();
513        return browserContext;
514    }
515
516    /// <summary>
517    /// <para>
518    /// Routing provides the capability to modify network requests that are made by any
519    /// page in the browser context. Once route is enabled, every request matching the url
520    /// pattern will stall unless it's continued, fulfilled or aborted.
521    /// </para>
522    /// <para>An example of a naive handler that aborts all image requests:</para>
523    /// <code>
524    /// var context = await browser.NewContextAsync();<br/>
525    /// var page = await context.NewPageAsync();<br/>
526    /// await context.RouteAsync("**/*.{png,jpg,jpeg}", r =&gt; r.AbortAsync());<br/>
527    /// await page.GotoAsync("https://theverge.com");<br/>
528    /// await browser.CloseAsync();
529    /// </code>
530    /// <para>or the same snippet using a regex pattern instead:</para>
531    /// <code>
532    /// var context = await browser.NewContextAsync();<br/>
533    /// var page = await context.NewPageAsync();<br/>
534    /// await context.RouteAsync(new Regex("(\\.png$)|(\\.jpg$)"), r =&gt; r.AbortAsync());<br/>
535    /// await page.GotoAsync("https://theverge.com");<br/>
536    /// await browser.CloseAsync();
537    /// </code>
538    /// <para>
539    /// It is possible to examine the request to decide the route action. For example, mocking
540    /// all requests that contain some post data, and leaving all other requests as is:
541    /// </para>
542    /// <code>
543    /// await page.RouteAsync("/api/**", async r =&gt;<br/>
544    /// {<br/>
545    ///     if (r.Request.PostData.Contains("my-string"))<br/>
546    ///         await r.FulfillAsync(body: "mocked-data");<br/>
547    ///     else<br/>
548    ///         await r.ContinueAsync();<br/>
549    /// });
550    /// </code>
551    /// <para>
552    /// Page routes (set up with <see cref="IPage.RouteAsync"/>) take precedence over browser
553    /// context routes when request matches both handlers.
554    /// </para>
555    /// <para>To remove a route with its handler you can use <see cref="IBrowserContext.UnrouteAsync"/>.</para>
556    /// </summary>
557    /// <remarks>
558    /// <para>
559    /// <see cref="IPage.RouteAsync"/> will not intercept requests intercepted by Service
560    /// Worker. See <a href="https://github.com/microsoft/playwright/issues/1090">this</a>
561    /// issue. We recommend disabling Service Workers when using request interception. Via
562    /// <c>await context.addInitScript(() =&gt; delete window.navigator.serviceWorker);</c>
563    /// </para>
564    /// <para>Enabling routing disables http cache.</para>
565    /// </remarks>
566    /// <param name="url">
567    /// A glob pattern, regex pattern or predicate receiving <see cref="URL"/> to match
568    /// while routing. When a <paramref name="baseURL"/> via the context options was provided
569    /// and the passed URL is a path, it gets merged via the <a href="https://developer.mozilla.org/en-US/docs/Web/API/URL/URL"><c>new
570    /// URL()</c></a> constructor.
571    /// </param>
572    /// <param name="handler">handler function to route the request.</param>
573    /// <param name="options">Call options</param>
574    public static IBrowserContext Route(this IBrowserContext browserContext, Func<string, bool> url, Action<IRoute> handler, BrowserContextRouteOptions? options = null)
575    {
576        browserContext.RouteAsync(url, handler, options).GetAwaiter().GetResult();
577        return browserContext;
578    }
579
580    /// <summary>
581    /// <para>
582    /// The extra HTTP headers will be sent with every request initiated by any page in
583    /// the context. These headers are merged with page-specific extra HTTP headers set
584    /// with <see cref="IPage.SetExtraHTTPHeadersAsync"/>. If page overrides a particular
585    /// header, page-specific header value will be used instead of the browser context header
586    /// value.
587    /// </para>
588    /// </summary>
589    /// <remarks>
590    /// <para>
591    /// <see cref="IBrowserContext.SetExtraHTTPHeadersAsync"/> does not guarantee the order
592    /// of headers in the outgoing requests.
593    /// </para>
594    /// </remarks>
595    /// <param name="headers">
596    /// An object containing additional HTTP headers to be sent with every request. All
597    /// header values must be strings.
598    /// </param>
599    public static IBrowserContext SetExtraHTTPHeaders(this IBrowserContext browserContext, IEnumerable<KeyValuePair<string, string>> headers)
600    {
601        browserContext.SetExtraHTTPHeadersAsync(headers).GetAwaiter().GetResult();
602        return browserContext;
603    }
604
605    /// <summary>
606    /// <para>
607    /// Sets the context's geolocation. Passing <c>null</c> or <c>undefined</c> emulates
608    /// position unavailable.
609    /// </para>
610    /// <code>
611    /// await context.SetGeolocationAsync(new Geolocation()<br/>
612    /// {<br/>
613    ///     Latitude = 59.95f,<br/>
614    ///     Longitude = 30.31667f<br/>
615    /// });
616    /// </code>
617    /// </summary>
618    /// <remarks>
619    /// <para>
620    /// Consider using <see cref="IBrowserContext.GrantPermissionsAsync"/> to grant permissions
621    /// for the browser context pages to read its geolocation.
622    /// </para>
623    /// </remarks>
624    /// <param name="geolocation">
625    /// </param>
626    public static IBrowserContext SetGeolocation(this IBrowserContext browserContext, Geolocation? geolocation)
627    {
628        browserContext.SetGeolocationAsync(geolocation).GetAwaiter().GetResult();
629        return browserContext;
630    }
631
632    /// <param name="offline">Whether to emulate network being offline for the browser context.</param>
633    public static IBrowserContext SetOffline(this IBrowserContext browserContext, bool offline)
634    {
635        browserContext.SetOfflineAsync(offline).GetAwaiter().GetResult();
636        return browserContext;
637    }
638
639    /// <summary>
640    /// <para>
641    /// Returns storage state for this browser context, contains current cookies and local
642    /// storage snapshot.
643    /// </para>
644    /// </summary>
645    /// <param name="options">Call options</param>
646    public static string StorageState(this IBrowserContext browserContext, BrowserContextStorageStateOptions? options = null)
647    {
648        return browserContext.StorageStateAsync(options).GetAwaiter().GetResult();
649    }
650
651    /// <summary>
652    /// <para>
653    /// Removes a route created with <see cref="IBrowserContext.RouteAsync"/>. When <paramref
654    /// name="handler"/> is not specified, removes all routes for the <paramref name="url"/>.
655    /// </para>
656    /// </summary>
657    /// <param name="url">
658    /// A glob pattern, regex pattern or predicate receiving <see cref="URL"/> used to register
659    /// a routing with <see cref="IBrowserContext.RouteAsync"/>.
660    /// </param>
661    /// <param name="handler">Optional handler function used to register a routing with <see cref="IBrowserContext.RouteAsync"/>.</param>
662    public static IBrowserContext Unroute(this IBrowserContext browserContext, string url, Action<IRoute>? handler = null)
663    {
664        browserContext.UnrouteAsync(url, handler).GetAwaiter().GetResult();
665        return browserContext;
666    }
667
668    /// <summary>
669    /// <para>
670    /// Removes a route created with <see cref="IBrowserContext.RouteAsync"/>. When <paramref
671    /// name="handler"/> is not specified, removes all routes for the <paramref name="url"/>.
672    /// </para>
673    /// </summary>
674    /// <param name="url">
675    /// A glob pattern, regex pattern or predicate receiving <see cref="URL"/> used to register
676    /// a routing with <see cref="IBrowserContext.RouteAsync"/>.
677    /// </param>
678    /// <param name="handler">Optional handler function used to register a routing with <see cref="IBrowserContext.RouteAsync"/>.</param>
679    public static IBrowserContext Unroute(this IBrowserContext browserContext, Regex url, Action<IRoute>? handler = null)
680    {
681        browserContext.UnrouteAsync(url, handler).GetAwaiter().GetResult();
682        return browserContext;
683    }
684
685    /// <summary>
686    /// <para>
687    /// Removes a route created with <see cref="IBrowserContext.RouteAsync"/>. When <paramref
688    /// name="handler"/> is not specified, removes all routes for the <paramref name="url"/>.
689    /// </para>
690    /// </summary>
691    /// <param name="url">
692    /// A glob pattern, regex pattern or predicate receiving <see cref="URL"/> used to register
693    /// a routing with <see cref="IBrowserContext.RouteAsync"/>.
694    /// </param>
695    /// <param name="handler">Optional handler function used to register a routing with <see cref="IBrowserContext.RouteAsync"/>.</param>
696    public static IBrowserContext Unroute(this IBrowserContext browserContext, Func<string, bool> url, Action<IRoute>? handler = null)
697    {
698        browserContext.UnrouteAsync(url, handler).GetAwaiter().GetResult();
699        return browserContext;
700    }
701
702    /// <summary>
703    /// <para>
704    /// Performs action and waits for a new <see cref="IPage"/> to be created in the context.
705    /// If predicate is provided, it passes <see cref="IPage"/> value into the <c>predicate</c>
706    /// function and waits for <c>predicate(event)</c> to return a truthy value. Will throw
707    /// an error if the context closes before new <see cref="IPage"/> is created.
708    /// </para>
709    /// </summary>
710    /// <param name="options">Call options</param>
711    public static IPage WaitForPage(this IBrowserContext browserContext, BrowserContextWaitForPageOptions? options = null)
712    {
713        return browserContext.WaitForPageAsync(options).GetAwaiter().GetResult();
714    }
715
716    /// <summary>
717    /// <para>
718    /// Performs action and waits for a new <see cref="IPage"/> to be created in the context.
719    /// If predicate is provided, it passes <see cref="IPage"/> value into the <c>predicate</c>
720    /// function and waits for <c>predicate(event)</c> to return a truthy value. Will throw
721    /// an error if the context closes before new <see cref="IPage"/> is created.
722    /// </para>
723    /// </summary>
724    /// <param name="action">Action that triggers the event.</param>
725    /// <param name="options">Call options</param>
726    public static IPage RunAndWaitForPage(this IBrowserContext browserContext, Func<Task> action, BrowserContextRunAndWaitForPageOptions? options = null)
727    {
728        return browserContext.RunAndWaitForPageAsync(action, options).GetAwaiter().GetResult();
729    }
730}
731
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 methods in BindingSource

    No methods found for this class 😞

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

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)