Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.BrowserContext.CloseAsync
Page.cs
Source:Page.cs
...345 await WrapApiBoundaryAsync(() => Task.WhenAll(result, action())).ConfigureAwait(false);346 }347 return await result.ConfigureAwait(false);348 }349 public async Task CloseAsync(PageCloseOptions options = default)350 {351 try352 {353 await _channel.CloseAsync(options?.RunBeforeUnload ?? false).ConfigureAwait(false);354 if (OwnedContext != null)355 {356 await OwnedContext.CloseAsync().ConfigureAwait(false);357 }358 }359 catch (Exception e) when (DriverMessages.IsSafeCloseError(e))360 {361 // Swallow exception362 }363 }364 public Task<T> EvaluateAsync<T>(string expression, object arg) => MainFrame.EvaluateAsync<T>(expression, arg);365 public Task<JsonElement?> EvalOnSelectorAsync(string selector, string expression, object arg) => MainFrame.EvalOnSelectorAsync(selector, expression, arg);366 public Task<T> EvalOnSelectorAsync<T>(string selector, string expression, object arg = null, PageEvalOnSelectorOptions options = null)367 => MainFrame.EvalOnSelectorAsync<T>(selector, expression, arg, new() { Strict = options?.Strict });368 public ILocator Locator(string selector, PageLocatorOptions options = default)369 => MainFrame.Locator(selector, new() { HasTextString = options?.HasTextString, HasTextRegex = options?.HasTextRegex, Has = options?.Has });370 public Task<IElementHandle> QuerySelectorAsync(string selector, PageQuerySelectorOptions options = null)...
BrowserTypeConnectTests.cs
Source:BrowserTypeConnectTests.cs
...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");...
Crawler.cs
Source:Crawler.cs
...317 return null;318 }319 finally320 {321 await page.CloseAsync(new PageCloseOptions { RunBeforeUnload = false });322 }323324 async Task<Uri> GetCanonicalUrl(IPage page)325 {326 var pageUrl = new Uri(page.Url, UriKind.Absolute);327 var link = await page.QuerySelectorAsync("link[rel=canonical]");328 if (link != null)329 {330 var href = await link.GetAttributeAsync("href");331 if (Uri.TryCreate(pageUrl, href, out var result))332 return result;333 }334335 return pageUrl;
...
BrowserContext.cs
Source:BrowserContext.cs
...131 return Channel.AddInitScriptAsync(script);132 }133 public Task ClearCookiesAsync() => Channel.ClearCookiesAsync();134 public Task ClearPermissionsAsync() => Channel.ClearPermissionsAsync();135 public async Task CloseAsync()136 {137 try138 {139 if (Options.RecordHarPath != null)140 {141 Artifact artifact = await Channel.HarExportAsync().ConfigureAwait(false);142 await artifact.SaveAsAsync(Options.RecordHarPath).ConfigureAwait(false);143 await artifact.DeleteAsync().ConfigureAwait(false);144 }145 await Channel.CloseAsync().ConfigureAwait(false);146 await _closeTcs.Task.ConfigureAwait(false);147 }148 catch (Exception e) when (DriverMessages.IsSafeCloseError(e))149 {150 // Swallow exception151 }152 }153 public Task<IReadOnlyList<BrowserContextCookiesResult>> CookiesAsync(IEnumerable<string> urls = null) => Channel.CookiesAsync(urls);154 public Task ExposeBindingAsync(string name, Action callback, BrowserContextExposeBindingOptions options = default)155 => ExposeBindingAsync(name, callback, handle: options?.Handle ?? false);156 public Task ExposeBindingAsync(string name, Action<BindingSource> callback)157 => ExposeBindingAsync(name, (Delegate)callback);158 public Task ExposeBindingAsync<T>(string name, Action<BindingSource, T> callback)159 => ExposeBindingAsync(name, (Delegate)callback);160 public Task ExposeBindingAsync<TResult>(string name, Func<BindingSource, TResult> callback)161 => ExposeBindingAsync(name, (Delegate)callback);162 public Task ExposeBindingAsync<TResult>(string name, Func<BindingSource, IJSHandle, TResult> callback)163 => ExposeBindingAsync(name, callback, true);164 public Task ExposeBindingAsync<T, TResult>(string name, Func<BindingSource, T, TResult> callback)165 => ExposeBindingAsync(name, (Delegate)callback);166 public Task ExposeBindingAsync<T1, T2, TResult>(string name, Func<BindingSource, T1, T2, TResult> callback)167 => ExposeBindingAsync(name, (Delegate)callback);168 public Task ExposeBindingAsync<T1, T2, T3, TResult>(string name, Func<BindingSource, T1, T2, T3, TResult> callback)169 => ExposeBindingAsync(name, (Delegate)callback);170 public Task ExposeBindingAsync<T1, T2, T3, T4, TResult>(string name, Func<BindingSource, T1, T2, T3, T4, TResult> callback)171 => ExposeBindingAsync(name, (Delegate)callback);172 public Task ExposeFunctionAsync(string name, Action callback)173 => ExposeBindingAsync(name, (BindingSource _) => callback());174 public Task ExposeFunctionAsync<T>(string name, Action<T> callback)175 => ExposeBindingAsync(name, (BindingSource _, T t) => callback(t));176 public Task ExposeFunctionAsync<TResult>(string name, Func<TResult> callback)177 => ExposeBindingAsync(name, (BindingSource _) => callback());178 public Task ExposeFunctionAsync<T, TResult>(string name, Func<T, TResult> callback)179 => ExposeBindingAsync(name, (BindingSource _, T t) => callback(t));180 public Task ExposeFunctionAsync<T1, T2, TResult>(string name, Func<T1, T2, TResult> callback)181 => ExposeBindingAsync(name, (BindingSource _, T1 t1, T2 t2) => callback(t1, t2));182 public Task ExposeFunctionAsync<T1, T2, T3, TResult>(string name, Func<T1, T2, T3, TResult> callback)183 => ExposeBindingAsync(name, (BindingSource _, T1 t1, T2 t2, T3 t3) => callback(t1, t2, t3));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(209 await Channel.GetStorageStateAsync().ConfigureAwait(false),210 JsonExtensions.DefaultJsonSerializerOptions);211 if (!string.IsNullOrEmpty(options?.Path))212 {213 File.WriteAllText(options?.Path, state);214 }215 return state;216 }217 public Task UnrouteAsync(string urlString, Action<IRoute> handler = default)218 => UnrouteAsync(new Regex(CombineUrlWithBase(urlString).GlobToRegex()), null, handler);219 public Task UnrouteAsync(Regex urlRegex, Action<IRoute> handler = default)220 => UnrouteAsync(urlRegex, null, handler);221 public Task UnrouteAsync(Func<string, bool> urlFunc, Action<IRoute> handler = default)222 => UnrouteAsync(null, urlFunc, handler);223 public async Task<T> InnerWaitForEventAsync<T>(PlaywrightEvent<T> playwrightEvent, Func<Task> action = default, Func<T, bool> predicate = default, float? timeout = default)224 {225 if (playwrightEvent == null)226 {227 throw new ArgumentException("Page event is required", nameof(playwrightEvent));228 }229 timeout ??= DefaultTimeout;230 using var waiter = new Waiter(this, $"context.WaitForEventAsync(\"{playwrightEvent.Name}\")");231 waiter.RejectOnTimeout(Convert.ToInt32(timeout), $"Timeout {timeout}ms exceeded while waiting for event \"{playwrightEvent.Name}\"");232 if (playwrightEvent.Name != BrowserContextEvent.Close.Name)233 {234 waiter.RejectOnEvent<IBrowserContext>(this, BrowserContextEvent.Close.Name, new("Context closed"));235 }236 var result = waiter.WaitForEventAsync(this, playwrightEvent.Name, predicate);237 if (action != null)238 {239 await WrapApiBoundaryAsync(() => Task.WhenAll(result, action())).ConfigureAwait(false);240 }241 return await result.ConfigureAwait(false);242 }243 public Task<IPage> WaitForPageAsync(BrowserContextWaitForPageOptions options = default)244 => InnerWaitForEventAsync(BrowserContextEvent.Page, null, options?.Predicate, options?.Timeout);245 public Task<IPage> RunAndWaitForPageAsync(Func<Task> action, BrowserContextRunAndWaitForPageOptions options = default)246 => InnerWaitForEventAsync(BrowserContextEvent.Page, action, options?.Predicate, options?.Timeout);247 public ValueTask DisposeAsync() => new ValueTask(CloseAsync());248 public void SetDefaultNavigationTimeout(float timeout) => DefaultNavigationTimeout = timeout;249 public void SetDefaultTimeout(float timeout) => DefaultTimeout = timeout;250 internal void OnRoute(Route route, IRequest request)251 {252 foreach (var routeHandler in _routes)253 {254 if (255 routeHandler.Regex?.IsMatch(request.Url) == true ||256 routeHandler.Function?.Invoke(request.Url) == true)257 {258 try259 {260 routeHandler.Handle(route);261 }...
BrowserContextBasicTests.cs
Source:BrowserContextBasicTests.cs
...40 await using var context = await browser.NewContextAsync();41 Assert.That(browser.Contexts, Has.Length.EqualTo(1));42 CollectionAssert.Contains(browser.Contexts, context);43 Assert.AreEqual(browser, context.Browser);44 await context.CloseAsync();45 Assert.IsEmpty(browser.Contexts);46 Assert.AreEqual(browser, context.Browser);47 }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 }...
BrowserType.cs
Source:BrowserType.cs
...137 }.ToDictionary(pair => pair.Key, pair => pair.Value);138 JsonPipe pipe = (await _channel.ConnectAsync(wsEndpoint: wsEndpoint, headers: headers, slowMo: options.SlowMo, timeout: options.Timeout).ConfigureAwait(false)).Object;139 void ClosePipe()140 {141 pipe.CloseAsync().IgnoreException();142 }143#pragma warning disable CA2000 // Dispose objects before losing scope144 var connection = new Connection();145#pragma warning restore CA2000146 connection.MarkAsRemote();147 connection.Close += (_, _) => ClosePipe();148 string closeError = null;149 Browser browser = null;150 void OnPipeClosed()151 {152 // Emulate all pages, contexts and the browser closing upon disconnect.153 foreach (BrowserContext context in browser?.BrowserContextsList.ToArray() ?? Array.Empty<BrowserContext>())154 {155 foreach (Page page in context.PagesList.ToArray())...
BrowserContextChannel.cs
Source:BrowserContextChannel.cs
...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,112 });113 internal Task SetDefaultTimeoutNoReplyAsync(float timeout)114 => Connection.SendMessageToServerAsync<PageChannel>(115 Guid,116 "setDefaultTimeoutNoReply",...
Browser.cs
Source:Browser.cs
...49 public string Version => _initializer.Version;50 internal BrowserChannel Channel { get; }51 internal List<BrowserContext> BrowserContextsList { get; } = new();52 internal LocalUtils LocalUtils { get; set; }53 public async Task CloseAsync()54 {55 try56 {57 if (ShouldCloseConnectionOnClose)58 {59 Channel.Connection.DoClose(DriverMessages.BrowserClosedExceptionMessage);60 }61 else62 {63 await Channel.CloseAsync().ConfigureAwait(false);64 }65 await _closedTcs.Task.ConfigureAwait(false);66 }67 catch (Exception e) when (DriverMessages.IsSafeCloseError(e))68 {69 // Swallow exception70 }71 }72 public async Task<IBrowserContext> NewContextAsync(BrowserNewContextOptions options = default)73 {74 options ??= new();75 var context = (await Channel.NewContextAsync(76 acceptDownloads: options.AcceptDownloads,77 bypassCSP: options.BypassCSP,78 colorScheme: options.ColorScheme,79 reducedMotion: options.ReducedMotion,80 deviceScaleFactor: options.DeviceScaleFactor,81 extraHTTPHeaders: options.ExtraHTTPHeaders,82 geolocation: options.Geolocation,83 hasTouch: options.HasTouch,84 httpCredentials: options.HttpCredentials,85 ignoreHTTPSErrors: options.IgnoreHTTPSErrors,86 isMobile: options.IsMobile,87 javaScriptEnabled: options.JavaScriptEnabled,88 locale: options.Locale,89 offline: options.Offline,90 permissions: options.Permissions,91 proxy: options.Proxy,92 recordHarOmitContent: options.RecordHarOmitContent,93 recordHarPath: options.RecordHarPath,94 recordVideo: GetVideoArgs(options.RecordVideoDir, options.RecordVideoSize),95 storageState: options.StorageState,96 storageStatePath: options.StorageStatePath,97 timezoneId: options.TimezoneId,98 userAgent: options.UserAgent,99 viewportSize: options.ViewportSize,100 screenSize: options.ScreenSize,101 baseUrl: options.BaseURL,102 strictSelectors: options.StrictSelectors,103 forcedColors: options.ForcedColors).ConfigureAwait(false)).Object;104 context.Options = options;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))160 {161 recordVideoArgs = new()162 {163 { "dir", recordVideoDir },164 };165 if (recordVideoSize != null)...
CloseAsync
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 await using var context = await browser.NewContextAsync();13 var page = await context.NewPageAsync();14 await page.CloseAsync();15 }16 }17}
CloseAsync
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 static async Task Main(string[] args)6 {7 using var playwright = await Playwright.CreateAsync();8 var browser = await playwright.Chromium.LaunchAsync();9 var context = await browser.NewContextAsync();10 var page = await context.NewPageAsync();11 Console.WriteLine(await page.TitleAsync());12 await context.CloseAsync();13 await browser.CloseAsync();14 }15}16public async Task CloseAsync()17using Microsoft.Playwright;18using System;19using System.Threading.Tasks;20{21 static async Task Main(string[] args)22 {23 using var playwright = await Playwright.CreateAsync();24 var browser = await playwright.Chromium.LaunchAsync();25 var context = await browser.NewContextAsync();26 var page = await context.NewPageAsync();27 Console.WriteLine(await page.TitleAsync());28 await context.CloseAsync();29 await browser.CloseAsync();30 }31}
CloseAsync
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();9 var context = await browser.NewContextAsync();10 var page = await context.NewPageAsync();11 await context.CloseAsync();12 }13 }14}
CloseAsync
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 await using var browser = await playwright.Chromium.LaunchAsync();11 var context = await browser.NewContextAsync();12 var page = await context.NewPageAsync();13 await context.CloseAsync();14 }15 }16}17using System;18using System.Threading.Tasks;19using Microsoft.Playwright;20using Microsoft.Playwright.Core;21{22 {23 static async Task Main(string[] args)24 {25 using var playwright = await Playwright.CreateAsync();26 await using var browser = await playwright.Chromium.LaunchAsync();27 var context = await browser.NewContextAsync();28 var page = await context.NewPageAsync();29 await context.CloseAsync();30 }31 }32}33using System;34using System.Threading.Tasks;35using Microsoft.Playwright;36using Microsoft.Playwright.Core;37{38 {39 static async Task Main(string[] args)40 {41 using var playwright = await Playwright.CreateAsync();42 await using var browser = await playwright.Chromium.LaunchAsync();43 var context = await browser.NewContextAsync();44 var page = await context.NewPageAsync();45 await context.CloseAsync();46 }47 }48}49using System;50using System.Threading.Tasks;51using Microsoft.Playwright;52using Microsoft.Playwright.Core;53{54 {55 static async Task Main(string
CloseAsync
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 await using var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions { Headless = false });11 var context = await browser.NewContextAsync();12 var page = await context.NewPageAsync();13 await page.CloseAsync();14 await context.CloseAsync();15 await browser.CloseAsync();16 }17 }18}19[PlaywrightTest] [2021-06-21T10:12:25.302Z] [browserType-launch] {"protocol":{"name":"browser","version":"1.3"},"sessionId":"0B8CFFB0C28F4C2B9C9F0A0D7E6B9A6C","capabilities":{"acceptInsecureCerts":false,"browserName":"chrome","browserVersion":"91.0.4472.114","chrome":{"chromedriverVersion":"91.0.4472.101 (5a3b4f4a9c2e2b4d4b6c1d6f8c6d4b0e4b3f4e4e)","userDataDir":"/tmp/playwright-0B8CFFB0C28F4C2B9C9F0A0D7E6B9A6C"},"goog:chromeOptions":{"debuggerAddress":"localhost:39459"},"networkConnectionEnabled":false,"pageLoadStrategy":"normal","platformName":"linux","proxy":{},"setWindowRect":true,"strictFileInteractability":false,"timeouts":{"implicit":0,"pageLoad":300000,"script":30000},"unhandledPromptBehavior":"dismiss and notify","webauthn:virtualAuthenticators":true}}
CloseAsync
Using AI Code Generation
1using Microsoft.Playwright;2var playwright = await Playwright.CreateAsync();3var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions4{5});6var context = await browser.NewContextAsync();7var page = await context.NewPageAsync();8await context.CloseAsync();9await browser.CloseAsync();
CloseAsync
Using AI Code Generation
1var browser = await Playwright.CreateAsync().Chromium.LaunchAsync();2var context = await browser.NewContextAsync();3var page = await context.NewPageAsync();4await context.CloseAsync();5await browser.CloseAsync();6var browser = await Playwright.CreateAsync().Chromium.LaunchAsync();7var context = await browser.NewContextAsync();8var page = await context.NewPageAsync();9await page.Context.CloseAsync();10await browser.CloseAsync();11var browser = await Playwright.CreateAsync().Chromium.LaunchAsync();12var context = await browser.NewContextAsync();13var page = await context.NewPageAsync();14await page.Context.CloseAsync();15await browser.CloseAsync();16var browser = await Playwright.CreateAsync().Chromium.LaunchAsync();17var context = await browser.NewContextAsync();18var page = await context.NewPageAsync();19await page.Context.CloseAsync();20await browser.CloseAsync();21var browser = await Playwright.CreateAsync().Chromium.LaunchAsync();22var context = await browser.NewContextAsync();23var page = await context.NewPageAsync();24await page.Context.CloseAsync();25await browser.CloseAsync();26var browser = await Playwright.CreateAsync().Chromium.LaunchAsync();27var context = await browser.NewContextAsync();28var page = await context.NewPageAsync();29await page.Context.CloseAsync();30await browser.CloseAsync();31var browser = await Playwright.CreateAsync().Chromium.LaunchAsync();
CloseAsync
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();10 var context = await browser.NewContextAsync();11 var page = await context.NewPageAsync();12 await context.CloseAsync();13 }14 }15}
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!!