Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.BrowserType
BrowserTypeConnectTests.cs
Source:BrowserTypeConnectTests.cs
...35using NUnit.Framework;36namespace Microsoft.Playwright.Tests37{38 ///<playwright-file>browsertype-connect.spec.ts</playwright-file>39 public class BrowserTypeConnectTests : PlaywrightTestEx40 {41 private RemoteServer _remoteServer;42 [SetUp]43 public void SetUpRemoteServer()44 {45 _remoteServer = new(BrowserType.Name);46 }47 [TearDown]48 public void TearDownRemoteServer()49 {50 _remoteServer.Close();51 }52 [PlaywrightTest("browsertype-connect.spec.ts", "should be able to reconnect to a browser")]53 public async Task ShouldBeAbleToReconnectToABrowser()54 {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]");...
Connection.cs
Source:Connection.cs
...232 case ChannelOwnerType.Browser:233 var browserInitializer = initializer?.ToObject<BrowserInitializer>(DefaultJsonSerializerOptions);234 result = new Browser(parent, guid, browserInitializer);235 break;236 case ChannelOwnerType.BrowserType:237 var browserTypeInitializer = initializer?.ToObject<BrowserTypeInitializer>(DefaultJsonSerializerOptions);238 result = new Core.BrowserType(parent, guid, browserTypeInitializer);239 break;240 case ChannelOwnerType.BrowserContext:241 var browserContextInitializer = initializer?.ToObject<BrowserContextInitializer>(DefaultJsonSerializerOptions);242 result = new BrowserContext(parent, guid, browserContextInitializer);243 break;244 case ChannelOwnerType.ConsoleMessage:245 result = new ConsoleMessage(parent, guid, initializer?.ToObject<ConsoleMessageInitializer>(DefaultJsonSerializerOptions));246 break;247 case ChannelOwnerType.Dialog:248 result = new Dialog(parent, guid, initializer?.ToObject<DialogInitializer>(DefaultJsonSerializerOptions));249 break;250 case ChannelOwnerType.ElementHandle:251 result = new ElementHandle(parent, guid, initializer?.ToObject<ElementHandleInitializer>(DefaultJsonSerializerOptions));252 break;...
BrowserContextBasicTests.cs
Source:BrowserContextBasicTests.cs
...34 {35 [PlaywrightTest("browsercontext-basic.spec.ts", "should create new context")]36 public async Task ShouldCreateNewContext()37 {38 await using var browser = await BrowserType.LaunchAsync();39 Assert.IsEmpty(browser.Contexts);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....
BrowserType.cs
Source:BrowserType.cs
...31using Microsoft.Playwright.Transport.Channels;32using Microsoft.Playwright.Transport.Protocol;33namespace Microsoft.Playwright.Core34{35 internal class BrowserType : ChannelOwnerBase, IChannelOwner<BrowserType>, IBrowserType36 {37 private readonly BrowserTypeInitializer _initializer;38 private readonly BrowserTypeChannel _channel;39 internal BrowserType(IChannelOwner parent, string guid, BrowserTypeInitializer initializer) : base(parent, guid)40 {41 _initializer = initializer;42 _channel = new(guid, parent.Connection, this);43 }44 ChannelBase IChannelOwner.Channel => _channel;45 IChannel<BrowserType> IChannelOwner<BrowserType>.Channel => _channel;46 internal PlaywrightImpl Playwright { get; set; }47 public string ExecutablePath => _initializer.ExecutablePath;48 public string Name => _initializer.Name;49 public async Task<IBrowser> LaunchAsync(BrowserTypeLaunchOptions options = default)50 {51 options ??= new BrowserTypeLaunchOptions();52 Browser browser = (await _channel.LaunchAsync(53 headless: options.Headless,54 channel: options.Channel,55 executablePath: options.ExecutablePath,56 passedArguments: options.Args,57 proxy: options.Proxy,58 downloadsPath: options.DownloadsPath,59 tracesDir: options.TracesDir,60 chromiumSandbox: options.ChromiumSandbox,61 firefoxUserPrefs: options.FirefoxUserPrefs,62 handleSIGINT: options.HandleSIGINT,63 handleSIGTERM: options.HandleSIGTERM,64 handleSIGHUP: options.HandleSIGHUP,65 timeout: options.Timeout,66 env: options.Env,67 devtools: options.Devtools,68 slowMo: options.SlowMo,69 ignoreDefaultArgs: options.IgnoreDefaultArgs,70 ignoreAllDefaultArgs: options.IgnoreAllDefaultArgs).ConfigureAwait(false)).Object;71 browser.LocalUtils = Playwright.Utils;72 return browser;73 }74 public async Task<IBrowserContext> LaunchPersistentContextAsync(string userDataDir, BrowserTypeLaunchPersistentContextOptions options = default)75 {76 options ??= new BrowserTypeLaunchPersistentContextOptions();77 var context = (await _channel.LaunchPersistentContextAsync(78 userDataDir,79 headless: options.Headless,80 channel: options.Channel,81 executablePath: options.ExecutablePath,82 args: options.Args,83 proxy: options.Proxy,84 downloadsPath: options.DownloadsPath,85 tracesDir: options.TracesDir,86 chromiumSandbox: options.ChromiumSandbox,87 handleSIGINT: options.HandleSIGINT,88 handleSIGTERM: options.HandleSIGTERM,89 handleSIGHUP: options.HandleSIGHUP,90 timeout: options.Timeout,91 env: options.Env,92 devtools: options.Devtools,93 slowMo: options.SlowMo,94 acceptDownloads: options.AcceptDownloads,95 ignoreHTTPSErrors: options.IgnoreHTTPSErrors,96 bypassCSP: options.BypassCSP,97 viewportSize: options.ViewportSize,98 screenSize: options.ScreenSize,99 userAgent: options.UserAgent,100 deviceScaleFactor: options.DeviceScaleFactor,101 isMobile: options.IsMobile,102 hasTouch: options.HasTouch,103 javaScriptEnabled: options.JavaScriptEnabled,104 timezoneId: options.TimezoneId,105 geolocation: options.Geolocation,106 locale: options.Locale,107 permissions: options.Permissions,108 extraHTTPHeaders: options.ExtraHTTPHeaders,109 offline: options.Offline,110 httpCredentials: options.HttpCredentials,111 colorScheme: options.ColorScheme,112 reducedMotion: options.ReducedMotion,113 recordHarPath: options.RecordHarPath,114 recordHarOmitContent: options.RecordHarOmitContent,115 recordVideo: Browser.GetVideoArgs(options.RecordVideoDir, options.RecordVideoSize),116 ignoreDefaultArgs: options.IgnoreDefaultArgs,117 ignoreAllDefaultArgs: options.IgnoreAllDefaultArgs,118 baseUrl: options.BaseURL,119 forcedColors: options.ForcedColors).ConfigureAwait(false)).Object;120 // TODO: unite with a single browser context options type which is derived from channels121 context.Options = new()122 {123 RecordVideoDir = options.RecordVideoDir,124 RecordVideoSize = options.RecordVideoSize,125 RecordHarPath = options.RecordHarPath,126 RecordHarOmitContent = options.RecordHarOmitContent,127 };128 ((Core.Tracing)context.Tracing).LocalUtils = Playwright.Utils;129 return context;130 }131 public async Task<IBrowser> ConnectAsync(string wsEndpoint, BrowserTypeConnectOptions options = null)132 {133 options ??= new BrowserTypeConnectOptions();134 var headers = new List<KeyValuePair<string, string>>(options.Headers ?? new Dictionary<string, string>())135 {136 new KeyValuePair<string, string>("x-playwright-browser", Name),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())156 {157 page.OnClose();158 }159 context.OnClose();160 }161 browser?.DidClose();162 connection.DoClose(closeError != null ? closeError : DriverMessages.BrowserClosedExceptionMessage);163 }164 pipe.Closed += (_, _) => OnPipeClosed();165 connection.OnMessage = async (object message) =>166 {167 try168 {169 await pipe.SendAsync(message).ConfigureAwait(false);170 }171 catch (Exception e) when (DriverMessages.IsSafeCloseError(e))172 {173 // swallow exception174 }175 catch176 {177 OnPipeClosed();178 }179 };180 pipe.Message += (_, message) =>181 {182 try183 {184 connection.Dispatch(message);185 }186 catch (Exception ex)187 {188 closeError = ex.ToString();189 _channel.Connection.TraceMessage("pw:dotnet", $"Dispatching error: {ex.Message}\n{ex.StackTrace}");190 ClosePipe();191 }192 };193 async Task<IBrowser> CreateBrowserAsync()194 {195 var playwright = await connection.InitializePlaywrightAsync().ConfigureAwait(false);196 playwright.Connection = connection;197 if (playwright.PreLaunchedBrowser == null)198 {199 ClosePipe();200 throw new ArgumentException("Malformed endpoint. Did you use launchServer method?");201 }202 browser = playwright.PreLaunchedBrowser;203 browser.ShouldCloseConnectionOnClose = true;204 browser.Disconnected += (_, _) => ClosePipe();205 browser.LocalUtils = Playwright.Utils;206 return playwright.PreLaunchedBrowser;207 }208 var task = CreateBrowserAsync();209 var timeout = options?.Timeout != null ? (int)options.Timeout : 30_000;210 return await task.WithTimeout(timeout, _ => throw new TimeoutException($"BrowserType.ConnectAsync: Timeout {options.Timeout}ms exceeded")).ConfigureAwait(false);211 }212 public async Task<IBrowser> ConnectOverCDPAsync(string endpointURL, BrowserTypeConnectOverCDPOptions options = null)213 {214 if (Name != "chromium")215 {216 throw new ArgumentException("Connecting over CDP is only supported in Chromium.");217 }218 options ??= new BrowserTypeConnectOverCDPOptions();219 JsonElement result = await _channel.ConnectOverCDPAsync(endpointURL, headers: options.Headers, slowMo: options.SlowMo, timeout: options.Timeout).ConfigureAwait(false);220 Browser browser = result.GetProperty("browser").ToObject<Browser>(_channel.Connection.DefaultJsonSerializerOptions);221 if (result.TryGetProperty("defaultContext", out JsonElement defaultContextValue))222 {223 browser.BrowserContextsList.Add(defaultContextValue.ToObject<BrowserContext>(_channel.Connection.DefaultJsonSerializerOptions));224 }225 browser.LocalUtils = Playwright.Utils;226 return browser;227 }228 }229}...
BrowserTypeChannel.cs
Source:BrowserTypeChannel.cs
...27using Microsoft.Playwright.Core;28using Microsoft.Playwright.Helpers;29namespace Microsoft.Playwright.Transport.Channels30{31 internal class BrowserTypeChannel : Channel<Core.BrowserType>32 {33 public BrowserTypeChannel(string guid, Connection connection, Core.BrowserType owner) : base(guid, connection, owner)34 {35 }36 public Task<BrowserChannel> LaunchAsync(37 bool? headless = default,38 string channel = default,39 string executablePath = default,40 IEnumerable<string> passedArguments = default,41 Proxy proxy = default,42 string downloadsPath = default,43 string tracesDir = default,44 bool? chromiumSandbox = default,45 IEnumerable<KeyValuePair<string, object>> firefoxUserPrefs = default,46 bool? handleSIGINT = default,47 bool? handleSIGTERM = default,...
PlaywrightImpl.cs
Source:PlaywrightImpl.cs
...58 ~PlaywrightImpl() => Dispose(false);59 Connection IChannelOwner.Connection => _connection;60 ChannelBase IChannelOwner.Channel => _channel;61 IChannel<PlaywrightImpl> IChannelOwner<PlaywrightImpl>.Channel => _channel;62 public IBrowserType Chromium { get => _initializer.Chromium; set => throw new NotSupportedException(); }63 public IBrowserType Firefox { get => _initializer.Firefox; set => throw new NotSupportedException(); }64 public IBrowserType Webkit { get => _initializer.Webkit; set => throw new NotSupportedException(); }65 public ISelectors Selectors => _initializer.Selectors;66 public IReadOnlyDictionary<string, BrowserNewContextOptions> Devices => _devices;67 internal Connection Connection { get; set; }68 internal Browser PreLaunchedBrowser => _initializer.PreLaunchedBrowser;69 internal LocalUtils Utils { get; set; }70 /// <summary>71 /// Gets a <see cref="IBrowserType"/>.72 /// </summary>73 /// <param name="browserType"><see cref="IBrowserType"/> name. You can get the names from <see cref="global::Microsoft.Playwright.BrowserType"/>.74 /// e.g.: <see cref="global::Microsoft.Playwright.BrowserType.Chromium"/>,75 /// <see cref="global::Microsoft.Playwright.BrowserType.Firefox"/> or <see cref="global::Microsoft.Playwright.BrowserType.Webkit"/>.76 /// </param>77 public IBrowserType this[string browserType]78 => browserType?.ToLower() switch79 {80 global::Microsoft.Playwright.BrowserType.Chromium => Chromium,81 global::Microsoft.Playwright.BrowserType.Firefox => Firefox,82 global::Microsoft.Playwright.BrowserType.Webkit => Webkit,83 _ => null,84 };85 public void Dispose()86 {87 Dispose(true);88 GC.SuppressFinalize(this);89 }90 private void Dispose(bool disposing)91 {92 if (!disposing)93 {94 return;95 }96 Connection?.Dispose();...
ProxyTests.cs
Source:ProxyTests.cs
...35 public async Task ShouldUseProxy()36 {37 Server.SetRoute("/target.html", ctx => ctx.Response.WriteAsync("<html><title>Served by the proxy</title></html>"));38 var proxy = new Proxy { Server = $"localhost:{Server.Port}" };39 await using var browser = await BrowserType.LaunchAsync(new() { Proxy = proxy });40 var page = await browser.NewPageAsync();41 await page.GotoAsync("http://non-existent.com/target.html");42 Assert.AreEqual("Served by the proxy", await page.TitleAsync());43 }44 [PlaywrightTest("proxy.spec.ts", "should authenticate")]45 public async Task ShouldAuthenticate()46 {47 Server.SetRoute("/target.html", ctx =>48 {49 string auth = ctx.Request.Headers["proxy-authorization"];50 if (string.IsNullOrEmpty(auth))51 {52 ctx.Response.StatusCode = 407;53 ctx.Response.Headers["Proxy-Authenticate"] = "Basic realm=\"Access to internal site\"";54 }55 return ctx.Response.WriteAsync($"<html><title>{auth}</title></html>");56 });57 var proxy = new Proxy58 {59 Server = $"localhost:{Server.Port}",60 Username = "user",61 Password = "secret"62 };63 await using var browser = await BrowserType.LaunchAsync(new() { Proxy = proxy });64 var page = await browser.NewPageAsync();65 await page.GotoAsync("http://non-existent.com/target.html");66 Assert.AreEqual("Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes("user:secret")), await page.TitleAsync());67 }68 [PlaywrightTest("proxy.spec.ts", "should exclude patterns")]69 public async Task ShouldExcludePatterns()70 {71 Server.SetRoute("/target.html", ctx => ctx.Response.WriteAsync("<html><title>Served by the proxy</title></html>"));72 var proxy = new Proxy73 {74 Server = $"localhost:{Server.Port}",75 Bypass = "non-existent1.com, .non-existent2.com, .another.test",76 };77 await using var browser = await BrowserType.LaunchAsync(new() { Proxy = proxy });78 var page = await browser.NewPageAsync();79 await page.GotoAsync("http://non-existent.com/target.html");80 Assert.AreEqual("Served by the proxy", await page.TitleAsync());81 await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.GotoAsync("http://non-existent1.com/target.html"));82 await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.GotoAsync("http://sub.non-existent2.com/target.html"));83 await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.GotoAsync("http://foo.is.the.another.test/target.html"));84 }85 }86}...
PlaywrightInitializer.cs
Source:PlaywrightInitializer.cs
...25namespace Microsoft.Playwright.Transport.Protocol26{27 internal class PlaywrightInitializer28 {29 public Core.BrowserType Chromium { get; set; }30 public Core.BrowserType Firefox { get; set; }31 public Core.BrowserType Webkit { get; set; }32 public Core.LocalUtils Utils { get; set; }33 public List<DeviceDescriptorEntry> DeviceDescriptors { get; set; }34 public Core.Selectors Selectors { get; set; }35 public Core.Browser PreLaunchedBrowser { get; set; }36 public Core.SocksSupport SocksSupport { get; set; }37 }38}...
BrowserType
Using AI Code Generation
1using Microsoft.Playwright.Core;2using Microsoft.Playwright;3using Microsoft.Playwright.Transport;4using Microsoft.Playwright.Transport.Channels;5using Microsoft.Playwright.Core;6using Microsoft.Playwright;7using Microsoft.Playwright.Transport;8using Microsoft.Playwright.Transport.Channels;9using Microsoft.Playwright.Core;10using Microsoft.Playwright;11using Microsoft.Playwright.Transport;12using Microsoft.Playwright.Transport.Channels;13using Microsoft.Playwright.Core;14using Microsoft.Playwright;15using Microsoft.Playwright.Transport;16using Microsoft.Playwright.Transport.Channels;17using Microsoft.Playwright.Core;18using Microsoft.Playwright;19using Microsoft.Playwright.Transport;20using Microsoft.Playwright.Transport.Channels;21using Microsoft.Playwright.Core;22using Microsoft.Playwright;23using Microsoft.Playwright.Transport;
BrowserType
Using AI Code Generation
1using Microsoft.Playwright;2using Microsoft.Playwright.Core;3using System;4using System.Collections.Generic;5using System.Linq;6using System.Text;7using System.Threading.Tasks;8{9 {10 static async Task Main(string[] args)11 {12 using var playwright = await Playwright.CreateAsync();13 var browserType = playwright.Chromium;14 var browser = await browserType.LaunchAsync();15 var page = await browser.NewPageAsync();16 await page.ScreenshotAsync(path: "google.png");17 await browser.CloseAsync();18 }19 }20}21using Microsoft.Playwright;22using Microsoft.Playwright.Core;23using System;24using System.Collections.Generic;25using System.Linq;26using System.Text;27using System.Threading.Tasks;28{29 {30 static async Task Main(string[] args)31 {32 using var playwright = await Playwright.CreateAsync();33 var browserType = playwright.Chromium;34 var browser = await browserType.LaunchAsync();35 var page = await browser.NewPageAsync();36 await page.ScreenshotAsync(path: "google.png");37 await browser.CloseAsync();38 }39 }40}41using Microsoft.Playwright;42using Microsoft.Playwright.Core;43using System;44using System.Collections.Generic;45using System.Linq;46using System.Text;47using System.Threading.Tasks;48{49 {50 static async Task Main(string[] args)51 {52 using var playwright = await Playwright.CreateAsync();53 var browserType = playwright.Chromium;54 var browser = await browserType.LaunchAsync();55 var page = await browser.NewPageAsync();56 await page.ScreenshotAsync(path: "google.png");57 await browser.CloseAsync();58 }59 }60}61using Microsoft.Playwright;62using Microsoft.Playwright.Core;63using System;64using System.Collections.Generic;65using System.Linq;66using System.Text;67using System.Threading.Tasks;68{
BrowserType
Using AI Code Generation
1var browserType = BrowserType.Chromium;2var browser = await browserType.LaunchAsync(new LaunchOptions { Headless = false });3var context = await browser.NewContextAsync();4var page = await context.NewPageAsync();5await page.ScreenshotAsync("google.png");6await browser.CloseAsync();7await context.CloseAsync();8var browserType = BrowserType.Chromium;9var browser = await browserType.LaunchAsync(new LaunchOptions { Headless = false });10var context = await browser.NewContextAsync();11var page = await context.NewPageAsync();12await page.ScreenshotAsync("google.png");13await browser.CloseAsync();14await context.CloseAsync();15var browserType = BrowserType.Chromium;16var browser = await browserType.LaunchAsync(new LaunchOptions { Headless = false });17var context = await browser.NewContextAsync();18var page = await context.NewPageAsync();19await page.ScreenshotAsync("google.png");20await browser.CloseAsync();21await context.CloseAsync();
BrowserType
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Playwright.Core;4{5 {6 static async Task Main(string[] args)7 {8 Console.WriteLine("Hello World!");9 var playwright = await Playwright.CreateAsync();10 var browser = await playwright.Firefox.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false });11 var context = await browser.NewContextAsync();12 var page = await context.NewPageAsync();13 await page.TypeAsync("input[aria-label='Search']", "Hello World");14 await page.PressAsync("input[aria-label='Search']", "Enter");15 await page.ScreenshotAsync(@"C:\Users\user\Desktop\PlaywrightTest\PlaywrightTest\bin\Debug\netcoreapp3.1\test.png");16 }17 }18}
BrowserType
Using AI Code Generation
1using Microsoft.Playwright.Core;2using System;3{4 {5 static async System.Threading.Tasks.Task Main(string[] args)6 {7 using var playwright = await Playwright.CreateAsync();8 var browser = await playwright.Firefox.LaunchAsync();9 var page = await browser.NewPageAsync();10 await page.ScreenshotAsync("msn.png");11 await browser.CloseAsync();12 }13 }14}
BrowserType
Using AI Code Generation
1using Microsoft.Playwright.Core;2using Microsoft.Playwright;3using Microsoft.Playwright.NUnit;4using Microsoft.Playwright.Core;5using Microsoft.Playwright;6using Microsoft.Playwright.NUnit;7using Microsoft.Playwright.Core;8using Microsoft.Playwright;9using Microsoft.Playwright.NUnit;10using Microsoft.Playwright.Core;11using Microsoft.Playwright;12using Microsoft.Playwright.NUnit;13using Microsoft.Playwright.Core;14using Microsoft.Playwright;15using Microsoft.Playwright.NUnit;16using Microsoft.Playwright.Core;17using Microsoft.Playwright;18using Microsoft.Playwright.NUnit;19using Microsoft.Playwright.Core;20using Microsoft.Playwright;21using Microsoft.Playwright.NUnit;22using Microsoft.Playwright.Core;23using Microsoft.Playwright;
BrowserType
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 var browser = await playwright.Chromium.LaunchAsync();9 var context = await browser.NewContextAsync();10 var page = await context.NewPageAsync();11 await page.ScreenshotAsync("google.png");12 await browser.CloseAsync();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 var browser = await playwright.Chromium.LaunchAsync();24 var context = await browser.NewContextAsync();25 var page = await context.NewPageAsync();26 await page.ScreenshotAsync("google.png");27 await browser.CloseAsync();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 var browser = await playwright.Chromium.LaunchAsync();39 var context = await browser.NewContextAsync();40 var page = await context.NewPageAsync();41 await page.ScreenshotAsync("google.png");42 await browser.CloseAsync();43 }44 }45}46using Microsoft.Playwright;47using System.Threading.Tasks;48{49 {50 static async Task Main(string[] args)51 {52 using var playwright = await Playwright.CreateAsync();53 var browser = await playwright.Chromium.LaunchAsync();54 var context = await browser.NewContextAsync();55 var page = await context.NewPageAsync();56 await page.ScreenshotAsync("google.png");
BrowserType
Using AI Code Generation
1using Microsoft.Playwright.Core;2{3 {4 static async Task Main(string[] args)5 {6 using var playwright = await Playwright.CreateAsync();7 var browserType = playwright.Chromium;8 var browser = await browserType.LaunchAsync(headless: false);9 var page = await browser.NewPageAsync();10 await page.ScreenshotAsync(path: "screenshot.png");11 await browser.CloseAsync();12 }13 }14}
BrowserType
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 var browserType = new BrowserType();9 var browser = await browserType.LaunchAsync();10 var page = await browser.NewPageAsync();11 Console.ReadLine();12 }13 }14}15using Microsoft.Playwright;16using System;17using System.Threading.Tasks;18{19 {20 static async Task Main(string[] args)21 {22 var browserType = new BrowserType();23 var browser = await browserType.LaunchAsync();24 var page = await browser.NewPageAsync();25 Console.ReadLine();26 }27 }28}29using Microsoft.Playwright;30using System;31using System.Threading.Tasks;32{33 {34 static async Task Main(string[] args)
BrowserType
Using AI Code Generation
1using Microsoft.Playwright.Core;2using System;3using System.Threading.Tasks;4{5{6static async Task Main(string[] args)7{8var browserType = new BrowserType();9var browser = await browserType.LaunchAsync(new LaunchOptions10{11});12var context = await browser.NewContextAsync();13var page = await context.NewPageAsync();14await browser.CloseAsync();15}16}17}
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!!