How to use BrowserContextExposeBindingOptions class of Microsoft.Playwright package

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

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

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

IBrowserContext.cs

Source: IBrowserContext.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.Threading.Tasks;
27
28namespace Microsoft.Playwright
29{
30    /// <summary>
31    /// <para>BrowserContexts provide a way to operate multiple independent browser sessions.</para>
32    /// <para>
33    /// If a page opens another page, e.g. with a <c>window.open</c> call, the popup will
34    /// belong to the parent page's browser context.
35    /// </para>
36    /// <para>
37    /// Playwright allows creation of "incognito" browser contexts with <c>browser.newContext()</c>
38    /// method. "Incognito" browser contexts don't write any browsing data to disk.
39    /// </para>
40    /// </summary>
41    public partial interface IBrowserContext : IAsyncDisposable
42    {
43        /// <inheritdoc cref="ExposeBindingAsync(string, Action, BrowserContextExposeBindingOptions)"/>
44        Task ExposeBindingAsync(string name, Action<BindingSource> callback);
45
46        /// <inheritdoc cref="ExposeBindingAsync(string, Action, BrowserContextExposeBindingOptions)"/>
47        Task ExposeBindingAsync<T>(string name, Action<BindingSource, T> callback);
48
49        /// <inheritdoc cref="ExposeBindingAsync(string, Action, BrowserContextExposeBindingOptions)"/>
50        Task ExposeBindingAsync<TResult>(string name, Func<BindingSource, TResult> callback);
51
52        /// <inheritdoc cref="ExposeBindingAsync(string, Action, BrowserContextExposeBindingOptions)"/>
53        Task ExposeBindingAsync<TResult>(string name, Func<BindingSource, IJSHandle, TResult> callback);
54
55        /// <inheritdoc cref="ExposeBindingAsync(string, Action, BrowserContextExposeBindingOptions)"/>
56        Task ExposeBindingAsync<T, TResult>(string name, Func<BindingSource, T, TResult> callback);
57
58        /// <inheritdoc cref="ExposeBindingAsync(string, Action, BrowserContextExposeBindingOptions)"/>
59        Task ExposeBindingAsync<T1, T2, TResult>(string name, Func<BindingSource, T1, T2, TResult> callback);
60
61        /// <inheritdoc cref="ExposeBindingAsync(string, Action, BrowserContextExposeBindingOptions)"/>
62        Task ExposeBindingAsync<T1, T2, T3, TResult>(string name, Func<BindingSource, T1, T2, T3, TResult> callback);
63
64        /// <inheritdoc cref="ExposeBindingAsync(string, Action, BrowserContextExposeBindingOptions)"/>
65        Task ExposeBindingAsync<T1, T2, T3, T4, TResult>(string name, Func<BindingSource, T1, T2, T3, T4, TResult> callback);
66
67        /// <inheritdoc cref="ExposeFunctionAsync(string, Action)"/>
68        Task ExposeFunctionAsync<T>(string name, Action<T> callback);
69
70        /// <inheritdoc cref="ExposeFunctionAsync(string, Action)"/>
71        Task ExposeFunctionAsync<TResult>(string name, Func<TResult> callback);
72
73        /// <inheritdoc cref="ExposeFunctionAsync(string, Action)"/>
74        Task ExposeFunctionAsync<T, TResult>(string name, Func<T, TResult> callback);
75
76        /// <inheritdoc cref="ExposeFunctionAsync(string, Action)"/>
77        Task ExposeFunctionAsync<T1, T2, TResult>(string name, Func<T1, T2, TResult> callback);
78
79        /// <inheritdoc cref="ExposeFunctionAsync(string, Action)"/>
80        Task ExposeFunctionAsync<T1, T2, T3, TResult>(string name, Func<T1, T2, T3, TResult> callback);
81
82        /// <inheritdoc cref="ExposeFunctionAsync(string, Action)"/>
83        Task ExposeFunctionAsync<T1, T2, T3, T4, TResult>(string name, Func<T1, T2, T3, T4, TResult> callback);
84    }
85}
86
Full Screen

BrowserContextExposeBindingOptions.cs

Source: BrowserContextExposeBindingOptions.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 BrowserContextExposeBindingOptions
43    {
44        public BrowserContextExposeBindingOptions() { }
45
46        public BrowserContextExposeBindingOptions(BrowserContextExposeBindingOptions clone)
47        {
48            if (clone == null)
49            {
50                return;
51            }
52
53            Handle = clone.Handle;
54        }
55
56        /// <summary>
57        /// <para>
58        /// Whether to pass the argument as a handle, instead of passing by value. When passing
59        /// a handle, only one argument is supported. When passing by value, multiple arguments
60        /// are supported.
61        /// </para>
62        /// </summary>
63        [JsonPropertyName("handle")]
64        public bool? Handle { get; set; }
65    }
66}
67
68#nullable disable
69
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 BrowserContextExposeBindingOptions

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)