Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.BrowserContext.NewPageAsync
BrowserTypeConnectTests.cs
Source:BrowserTypeConnectTests.cs
...55 {56 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);57 var browserContext = await browser.NewContextAsync();58 Assert.AreEqual(browserContext.Pages.Count, 0);59 var page = await browserContext.NewPageAsync();60 Assert.AreEqual(await page.EvaluateAsync<int>("11 * 11"), 121);61 await page.GotoAsync(Server.EmptyPage);62 await browser.CloseAsync();63 }64 {65 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);66 var browserContext = await browser.NewContextAsync();67 var page = await browserContext.NewPageAsync();68 await page.GotoAsync(Server.EmptyPage);69 await browser.CloseAsync();70 }71 }72 [PlaywrightTest("browsertype-connect.spec.ts", "should send default User-Agent and X-Playwright-Browser headers with connect request")]73 public async Task ShouldSendDefaultUserAgentAndPlaywrightBrowserHeadersWithConnectRequest()74 {75 var connectionRequest = Server.WaitForWebSocketConnectionRequest();76 BrowserType.ConnectAsync($"ws://localhost:{Server.Port}/ws", new()77 {78 Headers = new Dictionary<string, string>()79 {80 ["hello-foo"] = "i-am-bar",81 }82 }).IgnoreException();83 var request = await connectionRequest;84 StringAssert.Contains("Playwright", request.Headers["User-Agent"]);85 Assert.AreEqual(request.Headers["hello-foo"], "i-am-bar");86 Assert.AreEqual(request.Headers["x-playwright-browser"], BrowserType.Name);87 }88 [PlaywrightTest("browsertype-connect.spec.ts", "should be able to connect two browsers at the same time")]89 public async Task ShouldBeAbleToConnectTwoBrowsersAtTheSameTime()90 {91 var browser1 = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);92 Assert.AreEqual(browser1.Contexts.Count, 0);93 await browser1.NewContextAsync();94 Assert.AreEqual(browser1.Contexts.Count, 1);95 var browser2 = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);96 Assert.AreEqual(browser2.Contexts.Count, 0);97 await browser2.NewContextAsync();98 Assert.AreEqual(browser2.Contexts.Count, 1);99 Assert.AreEqual(browser1.Contexts.Count, 1);100 await browser1.CloseAsync();101 Assert.AreEqual(browser2.Contexts.Count, 1);102 var page2 = await browser2.NewPageAsync();103 Assert.AreEqual(await page2.EvaluateAsync<int>("7 * 6"), 42); // original browser should still work104 await browser2.CloseAsync();105 }106 [PlaywrightTest("browsertype-connect.spec.ts", "should timeout in connect while connecting")]107 [Skip(SkipAttribute.Targets.Windows)]108 public async Task ShouldTimeoutInConnectWhileConnecting()109 {110 var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(async () => await BrowserType.ConnectAsync($"ws://localhost:{Server.Port}/ws", new BrowserTypeConnectOptions { Timeout = 100 }));111 StringAssert.Contains("BrowserType.ConnectAsync: Timeout 100ms exceeded", exception.Message);112 }113 [PlaywrightTest("browsertype-connect.spec.ts", "should support slowmo option")]114 public async Task ShouldSupportSlowMo()115 {116 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint, new BrowserTypeConnectOptions { SlowMo = 200 });117 var start = DateTime.Now;118 var context = await browser.NewContextAsync();119 await browser.CloseAsync();120 Assert.Greater((DateTime.Now - start).TotalMilliseconds, 199);121 }122 [PlaywrightTest("browsertype-connect.spec.ts", "disconnected event should be emitted when browser is closed or server is closed")]123 public async Task DisconnectedEventShouldBeEmittedWhenBrowserIsClosedOrServerIsClosed()124 {125 var browser1 = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);126 await browser1.NewPageAsync();127 var browser2 = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);128 await browser2.NewPageAsync();129 int disconnected1 = 0;130 int disconnected2 = 0;131 browser1.Disconnected += (_, e) => disconnected1++;132 browser2.Disconnected += (_, e) => disconnected2++;133 var tsc1 = new TaskCompletionSource<object>();134 browser1.Disconnected += (_, e) => tsc1.SetResult(null);135 await browser1.CloseAsync();136 await tsc1.Task;137 Assert.AreEqual(disconnected1, 1);138 Assert.AreEqual(disconnected2, 0);139 var tsc2 = new TaskCompletionSource<object>();140 browser2.Disconnected += (_, e) => tsc2.SetResult(null);141 await browser2.CloseAsync();142 await tsc2.Task;143 Assert.AreEqual(disconnected1, 1);144 Assert.AreEqual(disconnected2, 1);145 }146 [PlaywrightTest("browsertype-connect.spec.ts", "disconnected event should have browser as argument")]147 public async Task DisconnectedEventShouldHaveBrowserAsArguments()148 {149 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);150 IBrowser disconneced = null;151 var tsc = new TaskCompletionSource<object>();152 browser.Disconnected += (_, browser) =>153 {154 disconneced = browser;155 tsc.SetResult(null);156 };157 await browser.CloseAsync();158 await tsc.Task;159 Assert.AreEqual(browser, disconneced);160 }161 [PlaywrightTest("browsertype-connect.spec.ts", "should set the browser connected state")]162 public async Task ShouldSetTheBrowserConnectedState()163 {164 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);165 Assert.AreEqual(browser.IsConnected, true);166 var tsc = new TaskCompletionSource<bool>();167 browser.Disconnected += (_, e) => tsc.SetResult(false);168 _remoteServer.Close();169 await tsc.Task;170 Assert.AreEqual(browser.IsConnected, false);171 }172 [PlaywrightTest("browsertype-connect.spec.ts", "should throw when used after isConnected returns false")]173 public async Task ShouldThrowWhenUsedAfterIsConnectedReturnsFalse()174 {175 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);176 var page = await browser.NewPageAsync();177 var tsc = new TaskCompletionSource<bool>();178 browser.Disconnected += (_, e) => tsc.SetResult(false);179 _remoteServer.Close();180 await tsc.Task;181 Assert.AreEqual(browser.IsConnected, false);182 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(async () => await page.EvaluateAsync("1 + 1"));183 StringAssert.Contains("has been closed", exception.Message);184 }185 [PlaywrightTest("browsertype-connect.spec.ts", "should throw when calling waitForNavigation after disconnect")]186 public async Task ShouldThrowWhenWhenCallingWaitForNavigationAfterDisconnect()187 {188 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);189 var page = await browser.NewPageAsync();190 var tsc = new TaskCompletionSource<bool>();191 browser.Disconnected += (_, e) => tsc.SetResult(false);192 _remoteServer.Close();193 await tsc.Task;194 Assert.AreEqual(browser.IsConnected, false);195 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(async () => await page.WaitForNavigationAsync());196 StringAssert.Contains("Navigation failed because page was closed", exception.Message);197 }198 [PlaywrightTest("browsertype-connect.spec.ts", "should reject navigation when browser closes")]199 public async Task ShouldRejectNavigationWhenBrowserCloses()200 {201 Server.SetRoute("/one-style.css", context =>202 {203 context.Response.Redirect("/one-style.css");204 return Task.CompletedTask;205 });206 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);207 var page = await browser.NewPageAsync();208 var PageGoto = page.GotoAsync(Server.Prefix + "/one-style.html", new PageGotoOptions { Timeout = 60000 });209 await Server.WaitForRequest("/one-style.css");210 await browser.CloseAsync();211 Assert.AreEqual(browser.IsConnected, false);212 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(async () => await PageGoto);213 StringAssert.Contains("has been closed", exception.Message);214 }215 [PlaywrightTest("browsertype-connect.spec.ts", "should reject waitForSelector when browser closes")]216 public async Task ShouldRejectWaitForSelectorWhenBrowserCloses()217 {218 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);219 var page = await browser.NewPageAsync();220 var watchdog = page.WaitForSelectorAsync("div");221 await browser.CloseAsync();222 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(async () => await watchdog);223 Assert.That(exception.Message, Contains.Substring("has been closed"));224 }225 [PlaywrightTest("browsertype-connect.spec.ts", "should emit close events on pages and contexts")]226 public async Task ShouldEmitCloseEventsOnPagesAndContexts()227 {228 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);229 var context = await browser.NewContextAsync();230 var tsc = new TaskCompletionSource<object>();231 context.Close += (_, e) => tsc.SetResult(null);232 var page = await context.NewPageAsync();233 bool pageClosed = false;234 page.Close += (_, e) => pageClosed = true;235 _remoteServer.Close();236 await tsc.Task;237 Assert.AreEqual(pageClosed, true);238 }239 [PlaywrightTest("browsertype-connect.spec.ts", "should terminate network waiters")]240 public async Task ShouldTerminateNetworkWaiters()241 {242 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);243 var page = await browser.NewPageAsync();244 var requestWatchdog = page.WaitForRequestAsync(Server.EmptyPage);245 var responseWatchog = page.WaitForResponseAsync(Server.EmptyPage);246 _remoteServer.Close();247 async Task CheckTaskHasException(Task task)248 {249 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(async () => await task);250 StringAssert.Contains("Page closed", exception.Message);251 StringAssert.DoesNotContain("Timeout", exception.Message);252 }253 await CheckTaskHasException(requestWatchdog);254 await CheckTaskHasException(responseWatchog);255 }256 [PlaywrightTest("browsertype-connect.spec.ts", "should not throw on close after disconnect")]257 public async Task ShouldNotThrowOnCloseAfterDisconnect()258 {259 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);260 var page = await browser.NewPageAsync();261 var tcs = new TaskCompletionSource<bool>();262 browser.Disconnected += (_, e) => tcs.SetResult(true);263 _remoteServer.Close();264 await tcs.Task;265 await browser.CloseAsync();266 }267 [PlaywrightTest("browsertype-connect.spec.ts", "should not throw on context.close after disconnect")]268 public async Task ShouldNotThrowOnContextCloseAfterDisconnect()269 {270 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);271 var context = await browser.NewContextAsync();272 await context.NewPageAsync();273 var tcs = new TaskCompletionSource<bool>();274 browser.Disconnected += (_, e) => tcs.SetResult(true);275 _remoteServer.Close();276 await tcs.Task;277 await context.CloseAsync();278 }279 [PlaywrightTest("browsertype-connect.spec.ts", "should not throw on page.close after disconnect")]280 public async Task ShouldNotThrowOnPageCloseAfterDisconnect()281 {282 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);283 var context = await browser.NewContextAsync();284 var page = await context.NewPageAsync();285 var tcs = new TaskCompletionSource<bool>();286 browser.Disconnected += (_, e) => tcs.SetResult(true);287 _remoteServer.Close();288 await tcs.Task;289 await page.CloseAsync();290 }291 [PlaywrightTest("browsertype-connect.spec.ts", "should saveAs videos from remote browser")]292 public async Task ShouldSaveAsVideosFromRemoteBrowser()293 {294 using var tempDirectory = new TempDirectory();295 var videoPath = tempDirectory.Path;296 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);297 var context = await browser.NewContextAsync(new()298 {299 RecordVideoDir = videoPath,300 RecordVideoSize = new() { Height = 320, Width = 240 }301 });302 var page = await context.NewPageAsync();303 await page.EvaluateAsync("() => document.body.style.backgroundColor = 'red'");304 await Task.Delay(1000);305 await context.CloseAsync();306 var videoSavePath = tempDirectory.Path + "my-video.webm";307 await page.Video.SaveAsAsync(videoSavePath);308 Assert.That(videoSavePath, Does.Exist);309 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(async () => await page.Video.PathAsync());310 StringAssert.Contains("Path is not available when connecting remotely. Use SaveAsAsync() to save a local copy", exception.Message);311 }312 [PlaywrightTest("browsertype-connect.spec.ts", "should save download")]313 public async Task ShouldSaveDownload()314 {315 Server.SetRoute("/download", context =>316 {317 context.Response.Headers["Content-Type"] = "application/octet-stream";318 context.Response.Headers["Content-Disposition"] = "attachment";319 return context.Response.WriteAsync("Hello world");320 });321 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);322 var page = await browser.NewPageAsync(new() { AcceptDownloads = true });323 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");324 var downloadTask = page.WaitForDownloadAsync();325 await TaskUtils.WhenAll(326 downloadTask,327 page.ClickAsync("a"));328 using var tmpDir = new TempDirectory();329 string userPath = Path.Combine(tmpDir.Path, "these", "are", "directories", "download.txt");330 var download = downloadTask.Result;331 await download.SaveAsAsync(userPath);332 Assert.True(new FileInfo(userPath).Exists);333 Assert.AreEqual("Hello world", File.ReadAllText(userPath));334 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => download.PathAsync());335 Assert.AreEqual("Path is not available when connecting remotely. Use SaveAsAsync() to save a local copy.", exception.Message);336 await browser.CloseAsync();337 }338 [PlaywrightTest("browsertype-connect.spec.ts", "should error when saving download after deletion")]339 public async Task ShouldErrorWhenSavingDownloadAfterDeletion()340 {341 Server.SetRoute("/download", context =>342 {343 context.Response.Headers["Content-Type"] = "application/octet-stream";344 context.Response.Headers["Content-Disposition"] = "attachment";345 return context.Response.WriteAsync("Hello world");346 });347 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);348 var page = await browser.NewPageAsync(new() { AcceptDownloads = true });349 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");350 var downloadTask = page.WaitForDownloadAsync();351 await TaskUtils.WhenAll(352 downloadTask,353 page.ClickAsync("a"));354 using var tmpDir = new TempDirectory();355 string userPath = Path.Combine(tmpDir.Path, "download.txt");356 var download = downloadTask.Result;357 await download.DeleteAsync();358 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => download.SaveAsAsync(userPath));359 StringAssert.Contains("Target page, context or browser has been closed", exception.Message);360 await browser.CloseAsync();361 }362 [PlaywrightTest("browsertype-connect.spec.ts", "should save har")]363 public async Task ShouldSaveHar()364 {365 using var tempDirectory = new TempDirectory();366 var harPath = tempDirectory.Path + "/test.har";367 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);368 var context = await browser.NewContextAsync(new()369 {370 RecordHarPath = harPath371 });372 var page = await context.NewPageAsync();373 await page.GotoAsync(Server.EmptyPage);374 await context.CloseAsync();375 await browser.CloseAsync();376 Assert.That(harPath, Does.Exist);377 var logString = System.IO.File.ReadAllText(harPath);378 StringAssert.Contains(Server.EmptyPage, logString);379 }380 [PlaywrightTest("browsertype-connect.spec.ts", "should record trace with sources")]381 public async Task ShouldRecordContextTraces()382 {383 using var tempDirectory = new TempDirectory();384 var tracePath = tempDirectory.Path + "/trace.zip";385 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);386 var context = await browser.NewContextAsync();387 var page = await context.NewPageAsync();388 await context.Tracing.StartAsync(new() { Sources = true });389 await page.GotoAsync(Server.EmptyPage);390 await page.SetContentAsync("<button>Click</button>");391 await page.ClickAsync("button");392 await context.Tracing.StopAsync(new TracingStopOptions { Path = tracePath });393 await browser.CloseAsync();394 Assert.That(tracePath, Does.Exist);395 ZipFile.ExtractToDirectory(tracePath, tempDirectory.Path);396 Assert.That(tempDirectory.Path + "/trace.trace", Does.Exist);397 Assert.That(tempDirectory.Path + "/trace.network", Does.Exist);398 Assert.AreEqual(1, Directory.GetFiles(Path.Join(tempDirectory.Path, "resources"), "*.txt").Length);399 }400 [PlaywrightTest("browsertype-connect.spec.ts", "should upload large file")]401 [Skip(SkipAttribute.Targets.Firefox, SkipAttribute.Targets.Webkit)]402 public async Task ShouldUploadLargeFile()403 {404 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);405 var context = await browser.NewContextAsync();406 var page = await context.NewPageAsync();407 await page.GotoAsync(Server.Prefix + "/input/fileupload.html");408 using var tmpDir = new TempDirectory();409 var filePath = Path.Combine(tmpDir.Path, "200MB");410 using (var stream = File.OpenWrite(filePath))411 {412 var str = new string('a', 4 * 1024);413 for (var i = 0; i < 50 * 1024; i++)414 {415 await stream.WriteAsync(Encoding.UTF8.GetBytes(str));416 }417 }418 var input = page.Locator("input[type=file]");419 var events = await input.EvaluateHandleAsync(@"e => {420 const events = [];...
Crawler.cs
Source:Crawler.cs
...198 }199200 private async Task<PageData?> AnalyzeUrlAsync(AnalyzeContext context)201 {202 var page = await context.BrowserContext.NewPageAsync();203 try204 {205 // perf: Enabling routing disables http cache206 await page.RouteAsync("**", async route =>207 {208 if (route.Request.ResourceType is "image" or "media" or "font")209 {210 await route.AbortAsync();211 }212 else213 {214 await route.ContinueAsync();215 }216 });
...
BrowserContext.cs
Source:BrowserContext.cs
...184 public Task ExposeFunctionAsync<T1, T2, T3, T4, TResult>(string name, Func<T1, T2, T3, T4, TResult> callback)185 => ExposeBindingAsync(name, (BindingSource _, T1 t1, T2 t2, T3 t3, T4 t4) => callback(t1, t2, t3, t4));186 public Task GrantPermissionsAsync(IEnumerable<string> permissions, BrowserContextGrantPermissionsOptions options = default)187 => Channel.GrantPermissionsAsync(permissions, options?.Origin);188 public async Task<IPage> NewPageAsync()189 {190 if (OwnerPage != null)191 {192 throw new PlaywrightException("Please use Browser.NewContextAsync()");193 }194 return (await Channel.NewPageAsync().ConfigureAwait(false)).Object;195 }196 public Task RouteAsync(string url, Action<IRoute> handler, BrowserContextRouteOptions options = default)197 => RouteAsync(new Regex(CombineUrlWithBase(url).GlobToRegex()), null, handler, options);198 public Task RouteAsync(Regex url, Action<IRoute> handler, BrowserContextRouteOptions options = default)199 => RouteAsync(url, null, handler, options);200 public Task RouteAsync(Func<string, bool> url, Action<IRoute> handler, BrowserContextRouteOptions options = default)201 => RouteAsync(null, url, handler, options);202 public Task SetExtraHTTPHeadersAsync(IEnumerable<KeyValuePair<string, string>> headers)203 => Channel.SetExtraHTTPHeadersAsync(headers);204 public Task SetGeolocationAsync(Geolocation geolocation) => Channel.SetGeolocationAsync(geolocation);205 public Task SetOfflineAsync(bool offline) => Channel.SetOfflineAsync(offline);206 public async Task<string> StorageStateAsync(BrowserContextStorageStateOptions options = default)207 {208 string state = JsonSerializer.Serialize(...
BrowserContextBasicTests.cs
Source:BrowserContextBasicTests.cs
...48 [PlaywrightTest("browsercontext-basic.spec.ts", "window.open should use parent tab context")]49 public async Task WindowOpenShouldUseParentTabContext()50 {51 await using var context = await Browser.NewContextAsync();52 var page = await context.NewPageAsync();53 await page.GotoAsync(Server.EmptyPage);54 var popupTargetCompletion = new TaskCompletionSource<IPage>();55 page.Popup += (_, e) => popupTargetCompletion.SetResult(e);56 var (popupTarget, _) = await TaskUtils.WhenAll(57 popupTargetCompletion.Task,58 page.EvaluateAsync("url => window.open(url)", Server.EmptyPage)59 );60 Assert.AreEqual(context, popupTarget.Context);61 await context.CloseAsync();62 }63 [PlaywrightTest("browsercontext-basic.spec.ts", "should isolate localStorage and cookies")]64 public async Task ShouldIsolateLocalStorageAndCookies()65 {66 // Create two incognito contexts.67 await using var browser = await BrowserType.LaunchAsync();68 var context1 = await browser.NewContextAsync();69 var context2 = await browser.NewContextAsync();70 Assert.IsEmpty(context1.Pages);71 Assert.IsEmpty(context2.Pages);72 // Create a page in first incognito context.73 var page1 = await context1.NewPageAsync();74 await page1.GotoAsync(Server.EmptyPage);75 await page1.EvaluateAsync(@"() => {76 localStorage.setItem('name', 'page1');77 document.cookie = 'name=page1';78 }");79 Assert.That(context1.Pages, Has.Count.EqualTo(1));80 Assert.IsEmpty(context2.Pages);81 // Create a page in second incognito context.82 var page2 = await context2.NewPageAsync();83 await page2.GotoAsync(Server.EmptyPage);84 await page2.EvaluateAsync(@"() => {85 localStorage.setItem('name', 'page2');86 document.cookie = 'name=page2';87 }");88 Assert.That(context1.Pages, Has.Count.EqualTo(1));89 Assert.AreEqual(page1, context1.Pages.FirstOrDefault());90 Assert.That(context2.Pages, Has.Count.EqualTo(1));91 Assert.AreEqual(page2, context2.Pages.FirstOrDefault());92 // Make sure pages don't share localstorage or cookies.93 Assert.AreEqual("page1", await page1.EvaluateAsync<string>("() => localStorage.getItem('name')"));94 Assert.AreEqual("name=page1", await page1.EvaluateAsync<string>("() => document.cookie"));95 Assert.AreEqual("page2", await page2.EvaluateAsync<string>("() => localStorage.getItem('name')"));96 Assert.AreEqual("name=page2", await page2.EvaluateAsync<string>("() => document.cookie"));97 // Cleanup contexts.98 await TaskUtils.WhenAll(context1.CloseAsync(), context2.CloseAsync());99 Assert.IsEmpty(browser.Contexts);100 }101 [PlaywrightTest("browsercontext-basic.spec.ts", "should propagate default viewport to the page")]102 public async Task ShouldPropagateDefaultViewportToThePage()103 {104 await using var context = await Browser.NewContextAsync(new()105 {106 ViewportSize = new()107 {108 Width = 456,109 Height = 789110 }111 });112 var page = await context.NewPageAsync();113 await TestUtils.VerifyViewportAsync(page, 456, 789);114 }115 [PlaywrightTest("browsercontext-basic.spec.ts", "should make a copy of default viewport")]116 public async Task ShouldMakeACopyOfDefaultViewport()117 {118 var viewport = new ViewportSize119 {120 Width = 456,121 Height = 789122 };123 await using var context = await Browser.NewContextAsync(new() { ViewportSize = viewport });124 viewport.Width = 567;125 var page = await context.NewPageAsync();126 await TestUtils.VerifyViewportAsync(page, 456, 789);127 }128 [PlaywrightTest("browsercontext-basic.spec.ts", "should respect deviceScaleFactor")]129 public async Task ShouldRespectDeviceScaleFactor()130 {131 await using var context = await Browser.NewContextAsync(new()132 {133 DeviceScaleFactor = 3134 });135 var page = await context.NewPageAsync();136 Assert.AreEqual(3, await page.EvaluateAsync<int>("window.devicePixelRatio"));137 }138 [PlaywrightTest("browsercontext-basic.spec.ts", "should not allow deviceScaleFactor with null viewport")]139 public async Task ShouldNotAllowDeviceScaleFactorWithViewportDisabled()140 {141 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Browser.NewContextAsync(new()142 {143 ViewportSize = ViewportSize.NoViewport,144 DeviceScaleFactor = 3,145 }));146 Assert.AreEqual("\"deviceScaleFactor\" option is not supported with null \"viewport\"", exception.Message);147 }148 [PlaywrightTest("browsercontext-basic.spec.ts", "should not allow isMobile with null viewport")]149 public async Task ShouldNotAllowIsMobileWithViewportDisabled()150 {151 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Browser.NewContextAsync(new()152 {153 ViewportSize = ViewportSize.NoViewport,154 IsMobile = true,155 }));156 Assert.AreEqual("\"isMobile\" option is not supported with null \"viewport\"", exception.Message);157 }158 [PlaywrightTest("browsercontext-basic.spec.ts", "close() should work for empty context")]159 public async Task CloseShouldWorkForEmptyContext()160 {161 var context = await Browser.NewContextAsync();162 await context.CloseAsync();163 }164 [PlaywrightTest("browsercontext-basic.spec.ts", "close() should abort waitForEvent")]165 public async Task CloseShouldAbortWaitForEvent()166 {167 var context = await Browser.NewContextAsync();168 var waitTask = context.WaitForPageAsync();169 await context.CloseAsync();170 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => waitTask);171 Assert.AreEqual("Context closed", exception.Message);172 }173 [PlaywrightTest("browsercontext-basic.spec.ts", "should not report frameless pages on error")]174 public async Task ShouldNotReportFramelessPagesOnError()175 {176 var context = await Browser.NewContextAsync();177 var page = await context.NewPageAsync();178 Server.SetRoute("/empty.html", context =>179 {180 context.Response.ContentType = "text/html";181 return context.Response.WriteAsync($"<a href=\"{Server.EmptyPage}\" target=\"_blank\">Click me</a>");182 });183 IPage popup = null;184 context.Page += (_, e) => popup = e;185 await page.GotoAsync(Server.EmptyPage);186 await page.ClickAsync("'Click me'");187 await context.CloseAsync();188 if (popup != null)189 {190 Assert.True(popup.IsClosed);191 Assert.NotNull(popup.MainFrame);192 }193 }194 [PlaywrightTest("browsercontext-basic.spec.ts", "close() should be callable twice")]195 public async Task CloseShouldBeCallableTwice()196 {197 var context = await Browser.NewContextAsync();198 await TaskUtils.WhenAll(context.CloseAsync(), context.CloseAsync());199 await context.CloseAsync();200 }201 [PlaywrightTest("browsercontext-basic.spec.ts", "should return all of the pages")]202 public async Task ShouldReturnAllOfThePages()203 {204 await using var context = await Browser.NewContextAsync();205 var page = await context.NewPageAsync();206 var second = await context.NewPageAsync();207 Assert.AreEqual(2, context.Pages.Count);208 CollectionAssert.Contains(context.Pages, page);209 CollectionAssert.Contains(context.Pages, second);210 }211 [PlaywrightTest("browsercontext-basic.spec.ts", "BrowserContext.pages()", "should close all belonging pages once closing context")]212 public async Task ShouldCloseAllBelongingPagesOnceClosingContext()213 {214 await using var context = await Browser.NewContextAsync();215 await context.NewPageAsync();216 Assert.That(context.Pages, Has.Count.EqualTo(1));217 await context.CloseAsync();218 Assert.IsEmpty(context.Pages);219 }220 [PlaywrightTest("browsercontext-basic.spec.ts", "should disable javascript")]221 public async Task ShouldDisableJavascript()222 {223 await using (var context = await Browser.NewContextAsync(new() { JavaScriptEnabled = false }))224 {225 var page = await context.NewPageAsync();226 await page.GotoAsync("data:text/html, <script>var something = 'forbidden'</script>");227 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.EvaluateAsync("something"));228 StringAssert.Contains(229 TestConstants.IsWebKit ? "Can't find variable: something" : "something is not defined",230 exception.Message);231 }232 await using (var context = await Browser.NewContextAsync())233 {234 var page = await context.NewPageAsync();235 await page.GotoAsync("data:text/html, <script>var something = 'forbidden'</script>");236 Assert.AreEqual("forbidden", await page.EvaluateAsync<string>("something"));237 }238 }239 [PlaywrightTest("browsercontext-basic.spec.ts", "should be able to navigate after disabling javascript")]240 public async Task ShouldBeAbleToNavigateAfterDisablingJavascript()241 {242 await using var context = await Browser.NewContextAsync(new() { JavaScriptEnabled = false });243 var page = await context.NewPageAsync();244 await page.GotoAsync(Server.EmptyPage);245 }246 [PlaywrightTest("browsercontext-basic.spec.ts", "should work with offline option")]247 public async Task ShouldWorkWithOfflineOption()248 {249 await using var context = await Browser.NewContextAsync(new() { Offline = true });250 var page = await context.NewPageAsync();251 await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.GotoAsync(Server.EmptyPage));252 await context.SetOfflineAsync(false);253 var response = await page.GotoAsync(Server.EmptyPage);254 Assert.AreEqual((int)HttpStatusCode.OK, response.Status);255 }256 [PlaywrightTest("browsercontext-basic.spec.ts", "should emulate navigator.onLine")]257 [Skip(SkipAttribute.Targets.Firefox)]258 public async Task ShouldEmulateNavigatorOnLine()259 {260 await using var context = await Browser.NewContextAsync();261 var page = await context.NewPageAsync();262 Assert.True(await page.EvaluateAsync<bool>("() => window.navigator.onLine"));263 await context.SetOfflineAsync(true);264 Assert.False(await page.EvaluateAsync<bool>("() => window.navigator.onLine"));265 await context.SetOfflineAsync(false);266 Assert.True(await page.EvaluateAsync<bool>("() => window.navigator.onLine"));267 }268 }269}...
BrowserContextChannel.cs
Source:BrowserContextChannel.cs
...93 Response?.Invoke(this, serverParams?.ToObject<BrowserContextChannelResponseEventArgs>(Connection.DefaultJsonSerializerOptions));94 break;95 }96 }97 internal Task<PageChannel> NewPageAsync()98 => Connection.SendMessageToServerAsync<PageChannel>(99 Guid,100 "newPage",101 null);102 internal Task CloseAsync() => Connection.SendMessageToServerAsync(Guid, "close");103 internal Task PauseAsync()104 => Connection.SendMessageToServerAsync(Guid, "pause", null);105 internal Task SetDefaultNavigationTimeoutNoReplyAsync(float timeout)106 => Connection.SendMessageToServerAsync<PageChannel>(107 Guid,108 "setDefaultNavigationTimeoutNoReply",109 new Dictionary<string, object>110 {111 ["timeout"] = timeout,...
Browser.cs
Source:Browser.cs
...105 ((Tracing)context.Tracing).LocalUtils = LocalUtils;106 BrowserContextsList.Add(context);107 return context;108 }109 public async Task<IPage> NewPageAsync(BrowserNewPageOptions options = default)110 {111 options ??= new();112 var contextOptions = new BrowserNewContextOptions()113 {114 AcceptDownloads = options.AcceptDownloads,115 IgnoreHTTPSErrors = options.IgnoreHTTPSErrors,116 BypassCSP = options.BypassCSP,117 ViewportSize = options.ViewportSize,118 ScreenSize = options.ScreenSize,119 UserAgent = options.UserAgent,120 DeviceScaleFactor = options.DeviceScaleFactor,121 IsMobile = options.IsMobile,122 HasTouch = options.HasTouch,123 JavaScriptEnabled = options.JavaScriptEnabled,124 TimezoneId = options.TimezoneId,125 Geolocation = options.Geolocation,126 Locale = options.Locale,127 Permissions = options.Permissions,128 ExtraHTTPHeaders = options.ExtraHTTPHeaders,129 Offline = options.Offline,130 HttpCredentials = options.HttpCredentials,131 ColorScheme = options.ColorScheme,132 ReducedMotion = options.ReducedMotion,133 ForcedColors = options.ForcedColors,134 RecordHarPath = options.RecordHarPath,135 RecordHarOmitContent = options.RecordHarOmitContent,136 RecordVideoDir = options.RecordVideoDir,137 RecordVideoSize = options.RecordVideoSize,138 Proxy = options.Proxy,139 StorageState = options.StorageState,140 StorageStatePath = options.StorageStatePath,141 BaseURL = options.BaseURL,142 StrictSelectors = options.StrictSelectors,143 };144 var context = (BrowserContext)await NewContextAsync(contextOptions).ConfigureAwait(false);145 var page = (Page)await context.NewPageAsync().ConfigureAwait(false);146 page.OwnedContext = context;147 context.Options = contextOptions;148 context.OwnerPage = page;149 return page;150 }151 public ValueTask DisposeAsync() => new ValueTask(CloseAsync());152 internal static Dictionary<string, object> GetVideoArgs(string recordVideoDir, RecordVideoSize recordVideoSize)153 {154 Dictionary<string, object> recordVideoArgs = null;155 if (recordVideoSize != null && string.IsNullOrEmpty(recordVideoDir))156 {157 throw new PlaywrightException("\"RecordVideoSize\" option requires \"RecordVideoDir\" to be specified");158 }159 if (!string.IsNullOrEmpty(recordVideoDir))...
BrowserContextStorageStateTests.cs
Source:BrowserContextStorageStateTests.cs
...32 {33 [PlaywrightTest("browsercontext-storage-state.spec.ts", "should capture local storage")]34 public async Task ShouldCaptureLocalStorage()35 {36 var page1 = await Context.NewPageAsync();37 await page1.RouteAsync("**/*", (route) =>38 {39 route.FulfillAsync(new() { Body = "<html></html>" });40 });41 await page1.GotoAsync("https://www.example.com");42 await page1.EvaluateAsync(@"() =>43 {44 localStorage['name1'] = 'value1';45 }");46 await page1.GotoAsync("https://www.domain.com");47 await page1.EvaluateAsync(@"() =>48 {49 localStorage['name2'] = 'value2';50 }");51 string storage = await Context.StorageStateAsync();52 // TODO: think about IVT-in the StorageState and serializing53 string expected = @"{""cookies"":[],""origins"":[{""origin"":""https://www.example.com"",""localStorage"":[{""name"":""name1"",""value"":""value1""}]},{""origin"":""https://www.domain.com"",""localStorage"":[{""name"":""name2"",""value"":""value2""}]}]}";54 Assert.AreEqual(expected, storage);55 }56 [PlaywrightTest("browsercontext-storage-state.spec.ts", "should set local storage")]57 public async Task ShouldSetLocalStorage()58 {59 var context = await Browser.NewContextAsync(new()60 {61 StorageState = "{\"cookies\":[],\"origins\":[{\"origin\":\"https://www.example.com\",\"localStorage\":[{\"name\":\"name1\",\"value\":\"value1\"}]}]}",62 });63 var page = await context.NewPageAsync();64 await page.RouteAsync("**/*", (route) =>65 {66 route.FulfillAsync(new() { Body = "<html></html>" });67 });68 await page.GotoAsync("https://www.example.com");69 var localStorage = await page.EvaluateAsync<string[]>("Object.keys(window.localStorage)");70 Assert.AreEqual(localStorage, new string[] { "name1" });71 var name1Value = await page.EvaluateAsync<string>("window.localStorage.getItem('name1')");72 Assert.AreEqual(name1Value, "value1");73 }74 [PlaywrightTest("browsercontext-storage-state.spec.ts", "should round-trip through the file")]75 public async Task ShouldRoundTripThroughTheFile()76 {77 var page1 = await Context.NewPageAsync();78 await page1.RouteAsync("**/*", (route) =>79 {80 route.FulfillAsync(new() { Body = "<html></html>" });81 });82 await page1.GotoAsync("https://www.example.com");83 await page1.EvaluateAsync(@"() =>84 {85 localStorage['name1'] = 'value1';86 document.cookie = 'username=John Doe';87 }");88 using var tempDir = new TempDirectory();89 string path = Path.Combine(tempDir.Path, "storage-state.json");90 string storage = await Context.StorageStateAsync(new() { Path = path });91 Assert.AreEqual(storage, File.ReadAllText(path));92 await using var context = await Browser.NewContextAsync(new() { StorageStatePath = path });93 var page2 = await context.NewPageAsync();94 await page2.RouteAsync("**/*", (route) =>95 {96 route.FulfillAsync(new() { Body = "<html></html>" });97 });98 await page2.GotoAsync("https://www.example.com");99 Assert.AreEqual("value1", await page2.EvaluateAsync<string>("localStorage['name1']"));100 Assert.AreEqual("username=John Doe", await page2.EvaluateAsync<string>("document.cookie"));101 }102 [PlaywrightTest("browsercontext-storage-state.spec.ts", "should capture cookies")]103 public async Task ShouldCaptureCookies()104 {105 Server.SetRoute("/setcookie.html", context =>106 {107 context.Response.Cookies.Append("a", "b");108 context.Response.Cookies.Append("empty", "");109 return Task.CompletedTask;110 });111 await Page.GotoAsync(Server.Prefix + "/setcookie.html");112 CollectionAssert.AreEqual(new[] { "a=b", "empty=" }, await Page.EvaluateAsync<string[]>(@"() =>113 {114 const cookies = document.cookie.split(';');115 return cookies.map(cookie => cookie.trim()).sort();116 }"));117 var storageState = await Context.StorageStateAsync();118 StringAssert.Contains(@"""name"":""a"",""value"":""b""", storageState);119 StringAssert.Contains(@"""name"":""empty"",""value"":""""", storageState);120 if (TestConstants.IsWebKit || TestConstants.IsFirefox)121 {122 StringAssert.Contains(@"""sameSite"":""None""", storageState);123 }124 else125 {126 StringAssert.Contains(@"""sameSite"":""Lax""", storageState);127 }128 StringAssert.DoesNotContain(@"""url"":null", storageState);129 await using var context2 = await Browser.NewContextAsync(new() { StorageState = storageState });130 var page2 = await context2.NewPageAsync();131 await page2.GotoAsync(Server.EmptyPage);132 CollectionAssert.AreEqual(new[] { "a=b", "empty=" }, await page2.EvaluateAsync<string[]>(@"() =>133 {134 const cookies = document.cookie.split(';');135 return cookies.map(cookie => cookie.trim()).sort();136 }"));137 }138 }139}...
PlaywrightDriverSetup.cs
Source:PlaywrightDriverSetup.cs
...36 {37 IgnoreHTTPSErrors = true,38 ViewportSize = ViewportSize.NoViewport39 });40 IPage page = await browserContext.NewPageAsync();41 _playwrightDriver = new PlaywrightDriver()42 {43 Playwright = playwright,44 Browser = browser,45 BrowserContext = browserContext,46 Page = page47 };48 }49 catch (Exception e)50 {51 Console.WriteLine(e);52 throw;53 }54 return _playwrightDriver;...
NewPageAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions10 {11 });12 var context = await browser.NewContextAsync(new BrowserNewContextOptions13 {14 });15 var page = await context.NewPageAsync();16 await page.ScreenshotAsync(new PageScreenshotOptions17 {18 });19 Console.WriteLine("Hello World!");20 }21 }22}23using System;24using System.Threading.Tasks;25using Microsoft.Playwright;26{27 {28 static async Task Main(string[] args)29 {30 using var playwright = await Playwright.CreateAsync();31 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions32 {33 });34 var context = await browser.NewContextAsync(new BrowserNewContextOptions35 {36 });37 var page = await browser.NewPageAsync();38 await page.ScreenshotAsync(new PageScreenshotOptions39 {40 });41 Console.WriteLine("Hello World!");42 }43 }44}45using System;46using System.Threading.Tasks;47using Microsoft.Playwright;48{49 {50 static async Task Main(string[] args)51 {52 using var playwright = await Playwright.CreateAsync();53 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions54 {55 });56 var context = await browser.NewContextAsync(new BrowserNewContextOptions57 {58 });59 var page = await playwright.NewPageAsync();60 await page.ScreenshotAsync(new
NewPageAsync
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 var browser = await playwright.Chromium.LaunchAsync();10 var context = await browser.NewContextAsync();11 var page = await context.NewPageAsync();12 await page.ScreenshotAsync("google.png");13 await browser.CloseAsync();14 }15 }16}
NewPageAsync
Using AI Code Generation
1using Microsoft.Playwright;2using System.Threading.Tasks;3{4 {5 static async Task Main(string[] args)6 {7 using var playwright = await Playwright.CreateAsync();8 await using var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions9 {10 });11 var context = await browser.NewContextAsync();12 var page = await context.NewPageAsync();13 }14 }15}16using Microsoft.Playwright;17using System.Threading.Tasks;18{19 {20 static async Task Main(string[] args)21 {22 using var playwright = await Playwright.CreateAsync();23 await using var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions24 {25 });26 var context = await browser.NewContextAsync();27 var page = await context.NewPageAsync();28 }29 }30}31using Microsoft.Playwright;32using System.Threading.Tasks;33{34 {35 static async Task Main(string[] args)36 {37 using var playwright = await Playwright.CreateAsync();38 await using var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions39 {40 });41 var context = await browser.NewContextAsync();42 var page = await context.NewPageAsync();43 await page.GotoAsync("
NewPageAsync
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 await using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Firefox.LaunchAsync(new BrowserTypeLaunchOptions10 {11 });12 var context = await browser.NewContextAsync(new BrowserNewContextOptions13 {14 {15 }16 });17 var page = await context.NewPageAsync(new BrowserNewPageOptions18 {19 });20 }21 }22}
NewPageAsync
Using AI Code Generation
1var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions2{3});4var context = await browser.NewContextAsync();5var page = await context.NewPageAsync();6await page.ScreenshotAsync("2.png");7await browser.CloseAsync();8var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions9{10});11var context = await browser.NewContextAsync();12var page = await context.NewPageAsync();13await page.ScreenshotAsync("3.png");14await browser.CloseAsync();15var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions16{17});18var context = await browser.NewContextAsync();19var page = await context.NewPageAsync();20await page.ScreenshotAsync("4.png");21await browser.CloseAsync();22var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions23{24});25var context = await browser.NewContextAsync();26var page = await context.NewPageAsync();27await page.ScreenshotAsync("5.png");28await browser.CloseAsync();29var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions30{31});32var context = await browser.NewContextAsync();33var page = await context.NewPageAsync();34await page.ScreenshotAsync("6.png");35await browser.CloseAsync();36var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions37{38});
NewPageAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4using Microsoft.Playwright.Core;5{6 {7 static async Task Main(string[] args)8 {9 using var playwright = await Playwright.CreateAsync();10 var browser = await playwright.Chromium.LaunchAsync();11 var context = await browser.NewContextAsync();12 var page = await context.NewPageAsync();13 await page.ScreenshotAsync("microsoft.png");14 await page.CloseAsync();15 await context.CloseAsync();16 await browser.CloseAsync();17 }18 }19}
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!