Best Puppeteer-sharp code snippet using PuppeteerSharp.Launcher.Launcher
PuppeteerLaunchTests.cs
Source:PuppeteerLaunchTests.cs
...10using PuppeteerSharp.Transport;11using PuppeteerSharp.Xunit;12using Xunit;13using Xunit.Abstractions;14namespace PuppeteerSharp.Tests.LauncherTests15{16 [Collection(TestConstants.TestFixtureCollectionName)]17 public class PuppeteerLaunchTests : PuppeteerBaseTest18 {19 public PuppeteerLaunchTests(ITestOutputHelper output) : base(output) { }20 [PuppeteerFact]21 public async Task ShouldWorkInRealLife()22 {23 var options = TestConstants.DefaultBrowserOptions();24 await using (var browser = await Puppeteer.LaunchAsync(options, TestConstants.LoggerFactory))25 await using (var page = await browser.NewPageAsync())26 {27 var response = await page.GoToAsync("https://www.google.com");28 Assert.Equal(HttpStatusCode.OK, response.Status);29 }30 }31 [PuppeteerTest("launcher.spec.ts", "Puppeteer.launch", "should reject all promises when browser is closed")]32 [PuppeteerFact]33 public async Task ShouldRejectAllPromisesWhenBrowserIsClosed()34 {35 await using (var browser = await Puppeteer.LaunchAsync(36 TestConstants.DefaultBrowserOptions(),37 TestConstants.LoggerFactory))38 await using (var page = await browser.NewPageAsync())39 {40 var neverResolves = page.EvaluateFunctionHandleAsync("() => new Promise(r => {})");41 await browser.CloseAsync();42 var exception = await Assert.ThrowsAsync<TargetClosedException>(() => neverResolves);43 Assert.Contains("Protocol error", exception.Message);44 }45 }46 [PuppeteerTest("launcher.spec.ts", "Puppeteer.launch", "should reject if executable path is invalid")]47 [PuppeteerFact]48 public async Task ShouldRejectIfExecutablePathIsInvalid()49 {50 var options = TestConstants.DefaultBrowserOptions();51 options.ExecutablePath = "random-invalid-path";52 var exception = await Assert.ThrowsAsync<FileNotFoundException>(() =>53 {54 return Puppeteer.LaunchAsync(options, TestConstants.LoggerFactory);55 });56 Assert.Contains("Failed to launch", exception.Message);57 Assert.Equal(options.ExecutablePath, exception.FileName);58 }59 [PuppeteerTest("launcher.spec.ts", "Puppeteer.launch", "userDataDir option")]60 [PuppeteerFact]61 public async Task UserDataDirOption()62 {63 using (var userDataDir = new TempDirectory())64 {65 var options = TestConstants.DefaultBrowserOptions();66 options.UserDataDir = userDataDir.Path;67 var launcher = new Launcher(TestConstants.LoggerFactory);68 await using (var browser = await launcher.LaunchAsync(options))69 {70 Assert.True(Directory.GetFiles(userDataDir.Path).Length > 0);71 await browser.CloseAsync();72 Assert.True(Directory.GetFiles(userDataDir.Path).Length > 0);73 }74 }75 }76 [PuppeteerTest("launcher.spec.ts", "Puppeteer.launch", "userDataDir argument")]77 [PuppeteerFact]78 public async Task UserDataDirArgument()79 {80 using (var userDataDir = new TempDirectory())81 {82 var launcher = new Launcher(TestConstants.LoggerFactory);83 var options = TestConstants.DefaultBrowserOptions();84 if (TestConstants.IsChrome)85 {86 options.Args = options.Args.Concat(new[] { $"--user-data-dir=\"{userDataDir}\"" }).ToArray();87 }88 else89 {90 options.Args = options.Args.Concat(new string[] { "-profile", userDataDir.ToString() }).ToArray();91 }92 await using (var browser = await launcher.LaunchAsync(options))93 {94 // Open a page to make sure its functional.95 await browser.NewPageAsync();96 Assert.True(Directory.GetFiles(userDataDir.Path).Length > 0);97 await browser.CloseAsync();98 Assert.True(Directory.GetFiles(userDataDir.Path).Length > 0);99 }100 }101 }102 [PuppeteerTest("launcher.spec.ts", "Puppeteer.launch", "userDataDir option should restore state")]103 [SkipBrowserFact(skipFirefox: true)]104 public async Task UserDataDirOptionShouldRestoreState()105 {106 using (var userDataDir = new TempDirectory())107 {108 var launcher = new Launcher(TestConstants.LoggerFactory);109 var options = TestConstants.DefaultBrowserOptions();110 if (TestConstants.IsChrome)111 {112 options.Args = options.Args.Concat(new[] { $"--user-data-dir=\"{userDataDir}\"" }).ToArray();113 }114 else115 {116 options.Args = options.Args.Concat(new string[] { "-profile", userDataDir.ToString() }).ToArray();117 }118 await using (var browser = await launcher.LaunchAsync(options))119 {120 var page = await browser.NewPageAsync();121 await page.GoToAsync(TestConstants.EmptyPage);122 await page.EvaluateExpressionAsync("localStorage.hey = 'hello'");123 }124 await using (var browser2 = await Puppeteer.LaunchAsync(options, TestConstants.LoggerFactory))125 {126 var page2 = await browser2.NewPageAsync();127 await page2.GoToAsync(TestConstants.EmptyPage);128 Assert.Equal("hello", await page2.EvaluateExpressionAsync<string>("localStorage.hey"));129 }130 }131 }132 [PuppeteerTest("launcher.spec.ts", "Puppeteer.launch", "userDataDir option should restore cookies")]133 [PuppeteerFact(Skip = "This mysteriously fails on Windows on AppVeyor.")]134 public async Task UserDataDirOptionShouldRestoreCookies()135 {136 using (var userDataDir = new TempDirectory())137 {138 var launcher = new Launcher(TestConstants.LoggerFactory);139 var options = TestConstants.DefaultBrowserOptions();140 options.Args = options.Args.Concat(new[] { $"--user-data-dir=\"{userDataDir}\"" }).ToArray();141 await using (var browser = await launcher.LaunchAsync(options))142 {143 var page = await browser.NewPageAsync();144 await page.GoToAsync(TestConstants.EmptyPage);145 await page.EvaluateExpressionAsync(146 "document.cookie = 'doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT'");147 }148 await TestUtils.WaitForCookieInChromiumFileAsync(userDataDir.Path, "doSomethingOnlyOnce");149 await using (var browser2 = await Puppeteer.LaunchAsync(options, TestConstants.LoggerFactory))150 {151 var page2 = await browser2.NewPageAsync();152 await page2.GoToAsync(TestConstants.EmptyPage);153 Assert.Equal("doSomethingOnlyOnce=true", await page2.EvaluateExpressionAsync<string>("document.cookie"));154 }155 }156 }157 [PuppeteerTest("launcher.spec.ts", "Puppeteer.launch", "should return the default arguments")]158 [PuppeteerFact]159 public void ShouldReturnTheDefaultArguments()160 {161 Assert.Contains("--headless", Puppeteer.GetDefaultArgs(TestConstants.DefaultBrowserOptions()));162 Assert.DoesNotContain("--headless", Puppeteer.GetDefaultArgs(new LaunchOptions163 {164 Headless = false165 }));166 if (TestConstants.IsChrome)167 {168 Assert.Contains("--no-first-run", Puppeteer.GetDefaultArgs(TestConstants.DefaultBrowserOptions()));169 Assert.Contains("--user-data-dir=\"foo\"", Puppeteer.GetDefaultArgs(new LaunchOptions170 {171 UserDataDir = "foo"172 }));173 }174 else175 {176 Assert.Contains("--no-remote", Puppeteer.GetDefaultArgs(TestConstants.DefaultBrowserOptions()));177 Assert.Contains("--foreground", Puppeteer.GetDefaultArgs(TestConstants.DefaultBrowserOptions()));178 Assert.Contains("--profile", Puppeteer.GetDefaultArgs(new LaunchOptions179 {180 UserDataDir = "foo",181 Product = TestConstants.IsChrome ? Product.Chrome : Product.Firefox,182 }));183 Assert.Contains("\"foo\"", Puppeteer.GetDefaultArgs(new LaunchOptions184 {185 UserDataDir = "foo",186 Product = TestConstants.IsChrome ? Product.Chrome : Product.Firefox,187 }));188 }189 }190 [Theory]191 [InlineData(false)]192 [InlineData(true)]193 public async Task ChromeShouldBeClosed(bool useDisposeAsync)194 {195 var options = TestConstants.DefaultBrowserOptions();196 var launcher = new Launcher(TestConstants.LoggerFactory);197 await using (var browser = await launcher.LaunchAsync(options))198 await using (var page = await browser.NewPageAsync())199 {200 var response = await page.GoToAsync(TestConstants.EmptyPage);201 Assert.Equal(HttpStatusCode.OK, response.Status);202 if (useDisposeAsync)203 {204 // emulates what would happen in a C#8 await using block205 await browser.DisposeAsync();206 }207 else208 {209 await browser.CloseAsync();210 }211 Assert.True(launcher.Process.HasExited);212 }213 }214 [PuppeteerFact]215 public async Task ChromeShouldBeClosedOnDispose()216 {217 var options = TestConstants.DefaultBrowserOptions();218 var launcher = new Launcher(TestConstants.LoggerFactory);219 await using (var browser = await launcher.LaunchAsync(options))220 await using (var page = await browser.NewPageAsync())221 {222 var response = await page.GoToAsync(TestConstants.EmptyPage);223 Assert.Equal(HttpStatusCode.OK, response.Status);224 }225 Assert.True(await launcher.Process.WaitForExitAsync(TimeSpan.FromSeconds(10)));226 Assert.True(launcher.Process.HasExited);227 }228 [PuppeteerFact]229 public async Task ShouldNotOpenTwoChromesUsingTheSameLauncher()230 {231 var launcher = new Launcher(TestConstants.LoggerFactory);232 await using (await launcher.LaunchAsync(TestConstants.DefaultBrowserOptions()))233 {234 var exception = await Assert.ThrowsAsync<InvalidOperationException>(() =>235 {236 return launcher.LaunchAsync(TestConstants.DefaultBrowserOptions());237 });238 Assert.Equal("Unable to create or connect to another process", exception.Message);239 }240 }241 [PuppeteerTest("launcher.spec.ts", "Puppeteer.launch", "should work with no default arguments")]242 [SkipBrowserFact(skipFirefox: true)]243 public async Task ShouldWorkWithNoDefaultArguments()244 {245 var options = TestConstants.DefaultBrowserOptions();...
PuppeteerConnectTests.cs
Source:PuppeteerConnectTests.cs
...7using Xunit.Abstractions;8using PuppeteerSharp.Helpers;9using PuppeteerSharp.Tests.Attributes;10using PuppeteerSharp.Xunit;11namespace PuppeteerSharp.Tests.LauncherTests12{13 [Collection(TestConstants.TestFixtureCollectionName)]14 public class PuppeteerConnectTests : PuppeteerBrowserBaseTest15 {16 public PuppeteerConnectTests(ITestOutputHelper output) : base(output)17 {18 }19 [PuppeteerTest("launcher.spec.ts", "Puppeteer.connect", "should be able to connect multiple times to the same browser")]20 [PuppeteerFact]21 public async Task ShouldBeAbleToConnectMultipleTimesToSameBrowser()22 {23 var options = new ConnectOptions()24 {25 BrowserWSEndpoint = Browser.WebSocketEndpoint...
FixturesTests.cs
Source:FixturesTests.cs
...34 public async Task ShouldCloseTheBrowserWhenTheConnectedProcessCloses()35 {36 var browserClosedTaskWrapper = new TaskCompletionSource<bool>();37 using var browserFetcher = new BrowserFetcher(Product.Chrome);38 var ChromiumLauncher = new ChromiumLauncher(39 (await browserFetcher.GetRevisionInfoAsync()).ExecutablePath,40 new LaunchOptions { Headless = true });41 await ChromiumLauncher.StartAsync().ConfigureAwait(false);42 var browser = await Puppeteer.ConnectAsync(new ConnectOptions43 {44 BrowserWSEndpoint = ChromiumLauncher.EndPoint45 });46 browser.Disconnected += (_, _) =>47 {48 browserClosedTaskWrapper.SetResult(true);49 };50 KillProcess(ChromiumLauncher.Process.Id);51 await browserClosedTaskWrapper.Task;52 Assert.True(browser.IsClosed);53 }54 [PuppeteerTest("fixtures.spec.ts", "Fixtures", "should close the browser when the node process closes")]55 [SkipBrowserFact(skipFirefox: true)]56 public async Task ShouldCloseTheBrowserWhenTheLaunchedProcessCloses()57 {58 var browserClosedTaskWrapper = new TaskCompletionSource<bool>();59 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }, TestConstants.LoggerFactory);60 browser.Disconnected += (_, _) =>61 {62 browserClosedTaskWrapper.SetResult(true);63 };64 KillProcess(browser.Launcher.Process.Id);65 await browserClosedTaskWrapper.Task;66 Assert.True(browser.IsClosed);67 }68 private void KillProcess(int pid)69 {70 var process = new Process();71 //We need to kill the process tree manually72 //See: https://github.com/dotnet/corefx/issues/2623473 if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))74 {75 process.StartInfo.FileName = "taskkill";76 process.StartInfo.Arguments = $"-pid {pid} -t -f";77 }78 else...
Program.cs
Source:Program.cs
...27 [28592:33396:0217/074915.471:ERROR:shader_disk_cache.cc(601)] Shader Cache Creation failed: -228 [28592:33396:0217/074915.473:ERROR:browser_gpu_channel_host_factory.cc(138)] Failed to launch GPU process.29 at PuppeteerSharp.ChromiumProcess.State.StartingState.StartCoreAsync(ChromiumProcess p)30 at PuppeteerSharp.ChromiumProcess.State.StartingState.StartCoreAsync(ChromiumProcess p)31 at PuppeteerSharp.Launcher.LaunchAsync(LaunchOptions options)32 at PuppeteerSharp.Launcher.LaunchAsync(LaunchOptions options)33 */34 KillPreviousWebBrowserProcesses();35 StartWebBrowser().Wait();36 }37 static void KillPreviousWebBrowserProcesses()38 {39 var matchingProcesses =40 System.Diagnostics.Process.GetProcesses()41 /*42 2020-02-1743 .Where(process => process.StartInfo.Arguments.Contains(UserDataDirPath(), StringComparison.InvariantCultureIgnoreCase))44 */45 .Where(ProcessIsWebBrowser)46 .ToList();...
HeadlessChromiumPuppeteerLauncher.cs
Source:HeadlessChromiumPuppeteerLauncher.cs
...3using System;4using System.Threading.Tasks;5namespace HeadlessChromium.Puppeteer.Lambda.Dotnet6{7 public class HeadlessChromiumPuppeteerLauncher8 {9 public static string[] DefaultChromeArgs = new[] 10 {11 "--disable-background-timer-throttling",12 "--disable-breakpad",13 "--disable-client-side-phishing-detection",14 "--disable-cloud-import",15 "--disable-default-apps",16 "--disable-dev-shm-usage",17 "--disable-extensions",18 "--disable-gesture-typing",19 "--disable-hang-monitor",20 "--disable-infobars",21 "--disable-notifications",22 "--disable-offer-store-unmasked-wallet-cards",23 "--disable-offer-upload-credit-cards",24 "--disable-popup-blocking",25 "--disable-print-preview",26 "--disable-prompt-on-repost",27 "--disable-setuid-sandbox",28 "--disable-speech-api",29 "--disable-sync",30 "--disable-tab-for-desktop-share",31 "--disable-translate",32 "--disable-voice-input",33 "--disable-wake-on-wifi",34 "--disk-cache-size=33554432",35 "--enable-async-dns",36 "--enable-simple-cache-backend",37 "--enable-tcp-fast-open",38 "--enable-webgl",39 "--hide-scrollbars",40 "--ignore-gpu-blacklist",41 "--media-cache-size=33554432",42 "--metrics-recording-only",43 "--mute-audio",44 "--no-default-browser-check",45 "--no-first-run",46 "--no-pings",47 "--no-sandbox",48 "--no-zygote",49 "--password-store=basic",50 "--prerender-from-omnibox=disabled",51 "--use-gl=swiftshader",52 "--use-mock-keychain",53 "--single-process",54 };55 private readonly ILoggerFactory loggerFactory;56 public HeadlessChromiumPuppeteerLauncher(ILoggerFactory loggerFactory)57 {58 this.loggerFactory = loggerFactory;59 }60 public Task<Browser> LaunchAsync()61 {62 return LaunchAsync(DefaultChromeArgs);63 }64 public async Task<Browser> LaunchAsync(string[] chromeArgs)65 {66 var chromeLocation = new ChromiumExtractor(loggerFactory).ExtractChromium();67 var launchOptions = new LaunchOptions()68 {69 ExecutablePath = chromeLocation,70 Args = chromeArgs,71 Headless = true72 };73 return await new Launcher(loggerFactory).LaunchAsync(launchOptions);74 }75 }76}...
BrowserDisconnectTests.cs
Source:BrowserDisconnectTests.cs
2using PuppeteerSharp.Tests.Attributes;3using PuppeteerSharp.Xunit;4using Xunit;5using Xunit.Abstractions;6namespace PuppeteerSharp.Tests.LauncherTests7{8 [Collection(TestConstants.TestFixtureCollectionName)]9 public class BrowserDisconnectTests : PuppeteerBrowserBaseTest10 {11 public BrowserDisconnectTests(ITestOutputHelper output) : base(output)12 {13 }14 [PuppeteerTest("launcher.spec.ts", "Browser.disconnect", "should reject navigation when browser closes")]15 [PuppeteerFact]16 public async Task ShouldRejectNavigationWhenBrowserCloses()17 {18 Server.SetRoute("/one-style.css", _ => Task.Delay(10000));19 await using (var browser = await Puppeteer.LaunchAsync(TestConstants.DefaultBrowserOptions()))20 {...
HtmlToPdfConverter.cs
Source:HtmlToPdfConverter.cs
...14 var downloadTask = Task.Run(() => new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision));15 downloadTask.Wait();16 if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))17 {18 var path = Launcher.GetExecutablePath();19 Bash($"chmod 777 {path}");20 }21 browser = Task.Run(() => Puppeteer.LaunchAsync(new LaunchOptions { Headless = true, Args = new string[] { "--no-sandbox" } })).Result;22 }23 private void Bash(string cmd)24 {25 var escapedArgs = cmd.Replace("\"", "\\\"");26 var process = new Process()27 {28 StartInfo = new ProcessStartInfo29 {30 FileName = "/bin/bash",31 Arguments = $"-c \"{escapedArgs}\"",32 RedirectStandardOutput = true,...
ExitingState.cs
Source:ExitingState.cs
...8 {9 public ExitingState(StateManager stateManager) : base(stateManager)10 {11 }12 public override Task EnterFromAsync(LauncherBase p, State fromState, TimeSpan timeout)13 => !StateManager.TryEnter(p, fromState, this) ? StateManager.CurrentState.ExitAsync(p, timeout) : ExitAsync(p, timeout);14 public override async Task ExitAsync(LauncherBase p, TimeSpan timeout)15 {16 var waitForExitTask = WaitForExitAsync(p);17 await waitForExitTask.WithTimeout(18 async () =>19 {20 await StateManager.Killing.EnterFromAsync(p, this, timeout).ConfigureAwait(false);21 await waitForExitTask.ConfigureAwait(false);22 },23 timeout,24 CancellationToken.None).ConfigureAwait(false);25 }26 public override Task KillAsync(LauncherBase p) => StateManager.Killing.EnterFromAsync(p, this);27 }28}...
Launcher
Using AI Code Generation
1using System;2using System.IO;3using System.Threading.Tasks;4using PuppeteerSharp;5{6 {7 static void Main(string[] args)8 {9 MainAsync().GetAwaiter().GetResult();10 }11 static async Task MainAsync()12 {13 {14 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"15 };16 using (var browser = await Puppeteer.LaunchAsync(options))17 using (var page = await browser.NewPageAsync())18 {19 await page.ScreenshotAsync("google.png");20 }21 }22 }23}24using System;25using System.IO;26using System.Threading.Tasks;27using PuppeteerSharp;28{29 {30 static void Main(string[] args)31 {32 MainAsync().GetAwaiter().GetResult();33 }34 static async Task MainAsync()35 {36 {37 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"38 };39 using (var browser = await Puppeteer.LaunchAsync(options))40 using (var page = await browser.NewPageAsync())41 {42 await page.ScreenshotAsync("google.png");43 }44 }45 }46}47using System;48using System.IO;49using System.Threading.Tasks;50using PuppeteerSharp;51{52 {53 static void Main(string[] args)54 {55 MainAsync().GetAwaiter().GetResult();56 }57 static async Task MainAsync()58 {59 {60 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"61 };62 using (var browser = Puppeteer.Launch
Launcher
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9 var browser = await Puppeteer.LaunchAsync(new LaunchOptions10 {11 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"12 });13 var page = await browser.NewPageAsync();14 await page.ScreenshotAsync("example.png");15 await browser.CloseAsync();16 }17 }18}
Launcher
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 static async Task Main(string[] args)6 {
Launcher
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9 var browser = await Puppeteer.LaunchAsync(new LaunchOptions10 {11 Args = new string[] { "--no-sandbox" }12 });13 var page = await browser.NewPageAsync();14 await page.ScreenshotAsync("google.png");15 await browser.CloseAsync();16 }17 }18}19using System;20using System.Threading.Tasks;21using PuppeteerSharp;22{23 {24 static async Task Main(string[] args)25 {26 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);27 var browser = await Puppeteer.LaunchAsync(new LaunchOptions28 {29 Args = new string[] { "--no-sandbox" }30 });31 var page = await browser.NewPageAsync();32 await page.ScreenshotAsync("google.png");33 await browser.CloseAsync();34 }35 }36}
Launcher
Using AI Code Generation
1using System;2using System.Diagnostics;3using System.Threading.Tasks;4using PuppeteerSharp;5{6 {7 static async Task Main(string[] args)8 {9 var browser = await Puppeteer.LaunchAsync(new LaunchOptions10 {11 Args = new string[] { "--no-sandbox" }12 });13 var page = await browser.NewPageAsync();14 await page.ScreenshotAsync("google.png");15 await page.CloseAsync();16 await browser.CloseAsync();17 var proc = Process.GetProcessesByName("chrome")[0];18 proc.Kill();19 proc.WaitForExit();20 proc.Close();21 }22 }23}24using System;25using System.Diagnostics;26using System.Threading.Tasks;27using PuppeteerSharp;28{29 {30 static async Task Main(string[] args)31 {32 var browser = await Puppeteer.LaunchAsync(new LaunchOptions33 {34 Args = new string[] { "--no-sandbox" }35 });36 var page = await browser.NewPageAsync();37 await page.ScreenshotAsync("google.png");38 await page.CloseAsync();
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!