From 30dd02409b890f38b4c5e81374b4ee60f4baf669 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?An=C5=BEe=20Vodovnik?= Date: Thu, 13 May 2021 19:25:16 +0200 Subject: [PATCH] docs(dotnet): BrowserContext and BrowserType (#6503) --- docs/src/api/class-browsercontext.md | 158 +++++++++++++++++++++++++++ docs/src/api/class-browsertype.md | 23 ++++ 2 files changed, 181 insertions(+) diff --git a/docs/src/api/class-browsercontext.md b/docs/src/api/class-browsercontext.md index 6bbdbb8631..c478049fc9 100644 --- a/docs/src/api/class-browsercontext.md +++ b/docs/src/api/class-browsercontext.md @@ -49,6 +49,18 @@ page.goto("https://example.com") context.close() ``` +```csharp +using var playwright = await Playwright.CreateAsync(); +var browser = await playwright.Firefox.LaunchAsync(headless: false); +// Create a new incognito browser context +var context = await browser.NewContextAsync(); +// Create a new page inside context. +var page = await context.NewPageAsync(); +await page.GoToAsync("https://bing.com"); +// Dispose context once it"s no longer needed. +await context.CloseAsync(); +``` + ## event: BrowserContext.backgroundPage * langs: js, python - argument: <[Page]> @@ -119,6 +131,13 @@ page = page_info.value print(page.evaluate("location.href")) ``` +```csharp +var popupTask = context.WaitForPageAsync(); +await Task.WhenAll(popupTask, page.ClickAsync("a")); + +Console.WriteLine(popupTask.Result.EvaluateAsync("location.href")); +``` + :::note Use [`method: Page.waitForLoadState`] to wait until the page gets to a particular state (you should not need it in most cases). @@ -155,6 +174,10 @@ await browser_context.add_cookies([cookie_object1, cookie_object2]) browser_context.add_cookies([cookie_object1, cookie_object2]) ``` +```csharp +await context.AddCookiesAsync(new[] { cookie1, cookie2 }); +``` + ### param: BrowserContext.addCookies.cookies - `cookies` <[Array]<[Object]>> - `name` <[string]> @@ -206,6 +229,10 @@ await browser_context.add_init_script(path="preload.js") browser_context.add_init_script(path="preload.js") ``` +```csharp +await context.AddInitScriptAsync(scriptPath: "preload.js"); +``` + :::note The order of evaluation of multiple scripts installed via [`method: BrowserContext.addInitScript`] and [`method: Page.addInitScript`] is not defined. @@ -283,6 +310,15 @@ context.grant_permissions(["clipboard-read"]) context.clear_permissions() ``` +```csharp +var context = await browser.NewContextAsync(); +await context.GrantPermissionsAsync(new[] { "clipboard-read" }); +// Alternatively, you can use the helper class ContextPermissions +// to specify the permissions... +// do stuff ... +await context.ClearPermissionsAsync(); +``` + ## async method: BrowserContext.close Closes the browser context. All the pages that belong to the browser context will be closed. @@ -421,6 +457,32 @@ with sync_playwright() as playwright: run(playwright) ``` +```csharp +using Microsoft.Playwright; +using System.Threading.Tasks; + +class Program +{ + public static async Task Main() + { + using var playwright = await Playwright.CreateAsync(); + var browser = await playwright.Webkit.LaunchAsync(headless: false); + var context = await browser.NewContextAsync(); + + await context.ExposeBindingAsync("pageURL", source => source.Page.Url); + var page = await context.NewPageAsync(); + await page.SetContentAsync("\n" + + "\n" + + "
"); + await page.ClickAsync("button"); + } +} +``` + An example of passing an element handle: ```js @@ -478,6 +540,26 @@ page.set_content(""" """) ``` +```csharp +var result = new TaskCompletionSource(); +var page = await Context.NewPageAsync(); +await Context.ExposeBindingAsync("clicked", async (BindingSource _, IJSHandle t) => +{ + return result.TrySetResult(await t.AsElement.TextContentAsync()); +}); + +await page.SetContentAsync("\n" + + "
Click me
\n" + + "
Or click me
\n"); + +await page.ClickAsync("div"); +// Note: it makes sense to await the result here, because otherwise, the context +// gets closed and the binding function will throw an exception. +Assert.Equal("Click me", await result.Task); +``` + ### param: BrowserContext.exposeBinding.name - `name` <[string]> @@ -632,6 +714,43 @@ with sync_playwright() as playwright: run(playwright) ``` +```csharp +using Microsoft.Playwright; +using System; +using System.Security.Cryptography; +using System.Threading.Tasks; + +class BrowserContextExamples +{ + public static async Task AddMd5FunctionToAllPagesInContext() + { + using var playwright = await Playwright.CreateAsync(); + var browser = await playwright.Webkit.LaunchAsync(headless: false); + var context = await browser.NewContextAsync(); + + // NOTE: md5 is inherently insecure, and we strongly discourage using + // this in production in any shape or form + await context.ExposeFunctionAsync("sha1", (string input) => + { + return Convert.ToBase64String( + MD5.Create().ComputeHash(System.Text.Encoding.UTF8.GetBytes(input))); + }); + + var page = await context.NewPageAsync(); + await page.SetContentAsync("\n" + + "\n" + + "
"); + + await page.ClickAsync("button"); + Console.WriteLine(await page.TextContentAsync("div")); + } +} +``` + ### param: BrowserContext.exposeFunction.name - `name` <[string]> @@ -737,6 +856,14 @@ page.goto("https://example.com") browser.close() ``` +```csharp +var context = await browser.NewContextAsync(); +var page = await context.NewPageAsync(); +await context.RouteAsync("**/*.{png,jpg,jpeg}", r => r.AbortAsync()); +await page.GoToAsync("https://theverge.com"); +await browser.CloseAsync(); +``` + or the same snippet using a regex pattern instead: ```js @@ -774,6 +901,14 @@ page.goto("https://example.com") browser.close() ``` +```csharp +var context = await browser.NewContextAsync(); +var page = await context.NewPageAsync(); +await context.RouteAsync(new Regex("(\\.png$)|(\\.jpg$)"), r => r.AbortAsync()); +await page.GoToAsync("https://theverge.com"); +await browser.CloseAsync(); +``` + It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is: ```js @@ -812,6 +947,16 @@ def handle_route(route): context.route("/api/**", handle_route) ``` +```csharp +await page.RouteAsync("/api/**", async r => +{ + if (r.Request.PostData.Contains("my-string")) + await r.FulfillAsync(body: "mocked-data"); + else + await r.ResumeAsync(); +}); +``` + Page routes (set up with [`method: Page.route`]) take precedence over browser context routes when request matches both handlers. @@ -917,6 +1062,14 @@ await browser_context.set_geolocation({"latitude": 59.95, "longitude": 30.31667} browser_context.set_geolocation({"latitude": 59.95, "longitude": 30.31667}) ``` +```csharp +await context.SetGeolocationAsync(new Geolocation() +{ + Latitude = 59.95f, + Longitude = 30.31667f +}); +``` + :::note Consider using [`method: BrowserContext.grantPermissions`] to grant permissions for the browser context pages to read its geolocation. @@ -1032,6 +1185,11 @@ with context.expect_event("page") as event_info: page = event_info.value ``` +```csharp +var t = page.WaitForEventAsync("page"); +await Task.WhenAll(t, page.ClickAsync("button")); +``` + ### param: BrowserContext.waitForEvent.event - `event` <[string]> diff --git a/docs/src/api/class-browsertype.md b/docs/src/api/class-browsertype.md index f8b892ab2b..5d026857c9 100644 --- a/docs/src/api/class-browsertype.md +++ b/docs/src/api/class-browsertype.md @@ -65,6 +65,25 @@ with sync_playwright() as playwright: run(playwright) ``` +```csharp +using Microsoft.Playwright; +using System.Threading.Tasks; + +class BrowserTypeExamples +{ + public static async Task Run() + { + using var playwright = await Playwright.CreateAsync(); + var chromium = playwright.Chromium; + var browser = await chromium.LaunchAsync(); + var page = await browser.NewPageAsync(); + await page.GoToAsync("https://www.bing.com"); + // other actions + await browser.CloseAsync(); + } +} +``` + ## async method: BrowserType.connect * langs: js, java, python - returns: <[Browser]> @@ -193,6 +212,10 @@ browser = playwright.chromium.launch( # or "firefox" or "webkit". ) ``` +```csharp +var browser = await playwright.Chromium.LaunchAsync(ignoreDefaultArgs: new[] { "--mute-audio" }) +``` + > **Chromium-only** Playwright can also be used to control the Google Chrome or Microsoft Edge browsers, but it works best with the version of Chromium it is bundled with. There is no guarantee it will work with any other version. Use [`option: executablePath`] option with extreme caution.