Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.BrowserType.LaunchAsync
DownloadTests.cs
Source:DownloadTests.cs
...362 }363 [PlaywrightTest("download.spec.ts", "should delete downloads on browser gone")]364 public async Task ShouldDeleteDownloadsOnBrowserGone()365 {366 var browser = await BrowserType.LaunchAsync();367 var page = await browser.NewPageAsync(new() { AcceptDownloads = true });368 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");369 var download1Task = page.WaitForDownloadAsync();370 await TaskUtils.WhenAll(371 download1Task,372 page.ClickAsync("a"));373 var download2Task = page.WaitForDownloadAsync();374 await TaskUtils.WhenAll(375 download2Task,376 page.ClickAsync("a"));377 string path1 = await download1Task.Result.PathAsync();378 string path2 = await download2Task.Result.PathAsync();379 Assert.True(new FileInfo(path1).Exists);380 Assert.True(new FileInfo(path2).Exists);381 await browser.CloseAsync();382 Assert.False(new FileInfo(path1).Exists);383 Assert.False(new FileInfo(path2).Exists);384 Assert.False(new FileInfo(Path.Combine(path1, "..")).Exists);385 }386 [PlaywrightTest("download.spec.ts", "should be able to cancel pending downloads")]387 public async Task ShouldBeAbleToCancelPendingDownload()388 {389 var browser = await BrowserType.LaunchAsync();390 var page = await browser.NewPageAsync(new() { AcceptDownloads = true });391 await page.SetContentAsync($"<a href=\"{Server.Prefix}/downloadWithDelay\">download</a>");392 var download = await page.RunAndWaitForDownloadAsync(() => page.ClickAsync("a"));393 await download.CancelAsync();394 var failure = await download.FailureAsync();395 Assert.AreEqual("canceled", failure);396 await page.CloseAsync();397 }398 [PlaywrightTest("download.spec.ts", "should not fail explicitly to cancel a download even if that is already finished")]399 public async Task ShouldNotFailWhenCancellingACompletedDownload()400 {401 var browser = await BrowserType.LaunchAsync();402 var page = await browser.NewPageAsync(new() { AcceptDownloads = true });403 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");404 var download = await page.RunAndWaitForDownloadAsync(() => page.ClickAsync("a"));405 using var tmpDir = new TempDirectory();406 string userPath = Path.Combine(tmpDir.Path, "download.txt");407 await download.SaveAsAsync(userPath);408 Assert.IsTrue(File.Exists(userPath));409 await download.CancelAsync();410 var failure = await download.FailureAsync();411 Assert.IsNull(failure);412 await page.CloseAsync();413 }414 [PlaywrightTest("download.spec.ts", "should report downloads with interception")]415 public async Task ShouldReportDownloadsWithInterception()416 {417 var browser = await BrowserType.LaunchAsync();418 var page = await browser.NewPageAsync(new() { AcceptDownloads = true });419 await page.RouteAsync("*", r => r.ContinueAsync());420 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");421 var download = await page.RunAndWaitForDownloadAsync(() => page.ClickAsync("a"));422 var path = await download.PathAsync();423 Assert.IsTrue(File.Exists(path));424 await page.CloseAsync();425 }426 }427}...
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
...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,...
BrowserTypeChannel.cs
Source:BrowserTypeChannel.cs
...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,48 bool? handleSIGHUP = default,49 float? timeout = default,50 IEnumerable<KeyValuePair<string, string>> env = default,...
PlaywrightBrowserManager.cs
Source:PlaywrightBrowserManager.cs
...40 cancellationToken.ThrowIfCancellationRequested();41 var playwright = await GetPlaywrightAsync(cancellationToken).ConfigureAwait(false);42 var browser = await browsersByInstanceId.GetOrAdd(43 instanceId,44 (instanceId) => new AsyncLazy<IBrowser>(async () => await (browserType ?? playwright.Chromium).LaunchAsync(browserTypeLaunchOptions).ConfigureAwait(false))45 )46 .WithCancellation(cancellationToken)47 .ConfigureAwait(false);48 using (await browser.AcquireLockAsync(cancellationToken).ConfigureAwait(false))49 {50 return await browser.NewContextAsync(browserNewContextOptions).ConfigureAwait(false);51 }52 }53 /// <summary>54 /// Closes the Playwright browser with the specified <paramref name="instanceId"/>, if it exists.55 /// </summary>56 /// <param name="instanceId">The instance ID of the browser to close</param>57 /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>58 /// <returns> <see langword="true"/> if the browser existed and was closed successfully; otherwise, <see langword="false"/></returns>...
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}...
PlaywrightDriverSetup.cs
Source:PlaywrightDriverSetup.cs
...22 IBrowser browser = null;23 switch (browserType)24 {25 case BrowserType.Chromium:26 browser = await playwright.Chromium.LaunchAsync(browserTypeLaunchOptions);27 break;28 case BrowserType.Firefox:29 browser = await playwright.Firefox.LaunchAsync(browserTypeLaunchOptions);30 break;31 case BrowserType.Webkit:32 browser = await playwright.Webkit.LaunchAsync(browserTypeLaunchOptions);33 break;34 }35 IBrowserContext browserContext = await browser.NewContextAsync(new BrowserNewContextOptions36 {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 = page...
LaunchAsync
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 var browserType = playwright.Chromium;10 {11 };12 var browser = await browserType.LaunchAsync(launchOptions);13 var context = await browser.NewContextAsync();14 var page = await context.NewPageAsync();15 await page.ScreenshotAsync("google.png");16 await browser.CloseAsync();17 }18 }19}20using System;21using System.Threading.Tasks;22using Microsoft.Playwright;23{24 {25 static async Task Main(string[] args)26 {27 using var playwright = await Playwright.CreateAsync();28 var browserType = playwright.Firefox;29 {30 };31 var browser = await browserType.LaunchAsync(launchOptions);32 var context = await browser.NewContextAsync();33 var page = await context.NewPageAsync();34 await page.ScreenshotAsync("google.png");35 await browser.CloseAsync();36 }37 }38}39using System;40using System.Threading.Tasks;41using Microsoft.Playwright;42{43 {44 static async Task Main(string[] args)45 {46 using var playwright = await Playwright.CreateAsync();47 var browserType = playwright.Webkit;48 {49 };50 var browser = await browserType.LaunchAsync(launchOptions);51 var context = await browser.NewContextAsync();52 var page = await context.NewPageAsync();53 await page.ScreenshotAsync("google.png");54 await browser.CloseAsync();55 }
LaunchAsync
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 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions10 {11 });12 var context = await browser.NewContextAsync();13 var page = await context.NewPageAsync();14 }15 }16}17using Microsoft.Playwright;18using System;19using System.Threading.Tasks;20{21 {22 static async Task Main(string[] args)23 {24 using var playwright = await Playwright.CreateAsync();25 await using var browser = await playwright.Firefox.LaunchAsync(new BrowserTypeLaunchOptions26 {27 });28 var context = await browser.NewContextAsync();29 var page = await context.NewPageAsync();30 }31 }32}33using Microsoft.Playwright;34using System;35using System.Threading.Tasks;36{37 {38 static async Task Main(string[] args)39 {40 using var playwright = await Playwright.CreateAsync();41 await using var browser = await playwright.Webkit.LaunchAsync(new BrowserTypeLaunchOptions42 {43 });44 var context = await browser.NewContextAsync();45 var page = await context.NewPageAsync();46 }47 }48}49using Microsoft.Playwright;50using System;51using System.Threading.Tasks;52{53 {54 static async Task Main(string[] args)55 {56 using var playwright = await Playwright.CreateAsync();57 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions58 {59 });
LaunchAsync
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 await using var browser = await playwright.Chromium.LaunchAsync(headless: false);14 var page = await browser.NewPageAsync();15 await page.ScreenshotAsync("google.png");16 }17 }18}19using Microsoft.Playwright;20using Microsoft.Playwright.Core;21using System;22using System.Collections.Generic;23using System.Linq;24using System.Text;25using System.Threading.Tasks;26{27 {28 static async Task Main(string[] args)29 {30 using var playwright = await Playwright.CreateAsync();31 await using var browser = await playwright.Firefox.LaunchAsync(headless: false);32 var page = await browser.NewPageAsync();33 await page.ScreenshotAsync("google.png");34 }35 }36}37using Microsoft.Playwright;38using Microsoft.Playwright.Core;39using System;40using System.Collections.Generic;41using System.Linq;42using System.Text;43using System.Threading.Tasks;44{45 {46 static async Task Main(string[] args)47 {48 using var playwright = await Playwright.CreateAsync();49 await using var browser = await playwright.Webkit.LaunchAsync(headless: false);50 var page = await browser.NewPageAsync();51 await page.ScreenshotAsync("google.png");52 }53 }54}55using Microsoft.Playwright;56using Microsoft.Playwright.Core;57using System;58using System.Collections.Generic;59using System.Linq;60using System.Text;61using System.Threading.Tasks;62{63 {64 static async Task Main(string[] args)65 {
LaunchAsync
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 chromium = playwright.Chromium;10 var browser = await chromium.LaunchAsync(headless: false);11 var page = await browser.NewPageAsync();12 await page.ScreenshotAsync(path: "screenshot.png");13 await browser.CloseAsync();14 }15 }16}17using Microsoft.Playwright;18using System;19using System.Threading.Tasks;20{21 {22 static async Task Main(string[] args)23 {24 using var playwright = await Playwright.CreateAsync();25 var chromium = playwright.Chromium;26 var browser = await chromium.LaunchAsync(headless: false);27 var page = await browser.NewPageAsync();28 await page.ScreenshotAsync(path: "screenshot.png");29 await browser.CloseAsync();30 }31 }32}33using Microsoft.Playwright;34using System;35using System.Threading.Tasks;36{37 {38 static async Task Main(string[] args)39 {40 using var playwright = await Playwright.CreateAsync();41 var chromium = playwright.Chromium;42 var browser = await chromium.LaunchAsync(headless: false);43 var page = await browser.NewPageAsync();44 await page.ScreenshotAsync(path: "screenshot.png");45 await browser.CloseAsync();46 }47 }48}49using Microsoft.Playwright;50using System;51using System.Threading.Tasks;52{53 {54 static async Task Main(string[] args)55 {56 using var playwright = await Playwright.CreateAsync();57 var chromium = playwright.Chromium;58 var browser = await chromium.LaunchAsync(headless: false);59 var page = await browser.NewPageAsync();
LaunchAsync
Using AI Code Generation
1using Microsoft.Playwright.Core;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 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 await page.ScreenshotAsync(new PageScreenshotOptions { Path = "google.png" });14 await browser.CloseAsync();15 }16 }17}18using Microsoft.Playwright.Core;19using System;20using System.Threading.Tasks;21{22 {23 static async Task Main(string[] args)24 {25 await using var playwright = await Playwright.CreateAsync();26 var browser = await playwright.Firefox.LaunchAsync(new BrowserTypeLaunchOptions27 {28 });29 var page = await browser.NewPageAsync();30 await page.ScreenshotAsync(new PageScreenshotOptions { Path = "google.png" });31 await browser.CloseAsync();32 }33 }34}35using Microsoft.Playwright.Core;36using System;37using System.Threading.Tasks;38{39 {40 static async Task Main(string[] args)41 {42 await using var playwright = await Playwright.CreateAsync();43 var browser = await playwright.Webkit.LaunchAsync(new BrowserTypeLaunchOptions44 {45 });46 var page = await browser.NewPageAsync();47 await page.ScreenshotAsync(new PageScreenshotOptions { Path = "google.png" });48 await browser.CloseAsync();49 }50 }51}52using Microsoft.Playwright.Core;53using System;54using System.Threading.Tasks;55{
LaunchAsync
Using AI Code Generation
1using Microsoft.Playwright.Core;2{3 {4 static async Task Main(string[] args)5 {6 await using var playwright = await Playwright.CreateAsync();7 await using var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions { Headless = false });8 var page = await browser.NewPageAsync();9 await page.ScreenshotAsync("bing.png");10 }11 }12}
LaunchAsync
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 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 await browser.CloseAsync();14 }15 }16}17using System;18using System.Threading.Tasks;19using Microsoft.Playwright;20{21 {22 static async Task Main(string[] args)23 {24 using var playwright = await Playwright.CreateAsync();25 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions26 {27 });28 var page = await browser.NewPageAsync();29 await page.WaitForSelectorAsync("input[title='Search']");30 await page.FillAsync("input[title='Search']", "playwright");31 await page.ClickAsync("input[value='Google Search']");32 await page.WaitForSelectorAsync("div[class='g']");33 await browser.CloseAsync();34 }35 }36}37using System;38using System.Threading.Tasks;39using Microsoft.Playwright;40{41 {42 static async Task Main(string[] args)43 {44 using var playwright = await Playwright.CreateAsync();45 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions46 {47 });
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!!