How to use LaunchAsync method of PuppeteerSharp.Launcher class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Launcher.LaunchAsync

PuppeteerLaunchTests.cs

Source:PuppeteerLaunchTests.cs Github

copy

Full Screen

...18 [Fact]19 public async Task ShouldWorkInRealLife()20 {21 var options = TestConstants.DefaultBrowserOptions();22 using (var browser = await Puppeteer.LaunchAsync(options, TestConstants.LoggerFactory))23 using (var page = await browser.NewPageAsync())24 {25 var response = await page.GoToAsync("https://www.google.com");26 Assert.Equal(HttpStatusCode.OK, response.Status);27 }28 }29 [Fact]30 public async Task ShouldWorkInRealLifeWithOptions()31 {32 var options = TestConstants.DefaultBrowserOptions();33 using (var browser = await Puppeteer.LaunchAsync(options, TestConstants.LoggerFactory))34 using (var page = await browser.NewPageAsync())35 {36 var response = await page.GoToAsync(37 "https://www.google.com",38 new NavigationOptions39 {40 Timeout = 10000,41 WaitUntil = new[] { WaitUntilNavigation.Networkidle0 }42 });43 Assert.Equal(HttpStatusCode.OK, response.Status);44 }45 }46 [Fact]47 public async Task ShouldRejectAllPromisesWhenBrowserIsClosed()48 {49 using (var browser = await Puppeteer.LaunchAsync(50 TestConstants.DefaultBrowserOptions(),51 TestConstants.LoggerFactory))52 using (var page = await browser.NewPageAsync())53 {54 var neverResolves = page.EvaluateFunctionHandleAsync("() => new Promise(r => {})");55 await browser.CloseAsync();56 var exception = await Assert.ThrowsAsync<TargetClosedException>(() => neverResolves);57 Assert.Contains("Protocol error", exception.Message);58 }59 }60 [Fact]61 public async Task ShouldRejectIfExecutablePathIsInvalid()62 {63 var options = TestConstants.DefaultBrowserOptions();64 options.ExecutablePath = "random-invalid-path";65 var exception = await Assert.ThrowsAsync<FileNotFoundException>(() =>66 {67 return Puppeteer.LaunchAsync(options, TestConstants.LoggerFactory);68 });69 Assert.Contains("Failed to launch", exception.Message);70 Assert.Equal(options.ExecutablePath, exception.FileName);71 }72 [Fact]73 public async Task UserDataDirOption()74 {75 using (var userDataDir = new TempDirectory())76 {77 var options = TestConstants.DefaultBrowserOptions();78 options.UserDataDir = userDataDir.Path;79 var launcher = new Launcher(TestConstants.LoggerFactory);80 using (var browser = await launcher.LaunchAsync(options))81 {82 Assert.True(Directory.GetFiles(userDataDir.Path).Length > 0);83 await browser.CloseAsync();84 Assert.True(Directory.GetFiles(userDataDir.Path).Length > 0);85 }86 }87 }88 [Fact]89 public async Task UserDataDirArgument()90 {91 using (var userDataDir = new TempDirectory())92 {93 var launcher = new Launcher(TestConstants.LoggerFactory);94 var options = TestConstants.DefaultBrowserOptions();95 options.Args = options.Args.Concat(new[] { $"--user-data-dir=\"{userDataDir}\"" }).ToArray();96 using (var browser = await launcher.LaunchAsync(options))97 {98 // Open a page to make sure its functional.99 await browser.NewPageAsync();100 Assert.True(Directory.GetFiles(userDataDir.Path).Length > 0);101 await browser.CloseAsync();102 Assert.True(Directory.GetFiles(userDataDir.Path).Length > 0);103 }104 }105 }106 [Fact]107 public async Task UserDataDirOptionShouldRestoreState()108 {109 using (var userDataDir = new TempDirectory())110 {111 var launcher = new Launcher(TestConstants.LoggerFactory);112 var options = TestConstants.DefaultBrowserOptions();113 options.Args = options.Args.Concat(new[] { $"--user-data-dir=\"{userDataDir}\"" }).ToArray();114 using (var browser = await launcher.LaunchAsync(options))115 {116 var page = await browser.NewPageAsync();117 await page.GoToAsync(TestConstants.EmptyPage);118 await page.EvaluateExpressionAsync("localStorage.hey = 'hello'");119 }120 using (var browser2 = await Puppeteer.LaunchAsync(options, TestConstants.LoggerFactory))121 {122 var page2 = await browser2.NewPageAsync();123 await page2.GoToAsync(TestConstants.EmptyPage);124 Assert.Equal("hello", await page2.EvaluateExpressionAsync<string>("localStorage.hey"));125 }126 }127 }128 [Fact(Skip = "This mysteriously fails on Windows on AppVeyor.")]129 public async Task UserDataDirOptionShouldRestoreCookies()130 {131 using (var userDataDir = new TempDirectory())132 {133 var launcher = new Launcher(TestConstants.LoggerFactory);134 var options = TestConstants.DefaultBrowserOptions();135 options.Args = options.Args.Concat(new[] { $"--user-data-dir=\"{userDataDir}\"" }).ToArray();136 using (var browser = await launcher.LaunchAsync(options))137 {138 var page = await browser.NewPageAsync();139 await page.GoToAsync(TestConstants.EmptyPage);140 await page.EvaluateExpressionAsync(141 "document.cookie = 'doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT'");142 }143 await TestUtils.WaitForCookieInChromiumFileAsync(userDataDir.Path, "doSomethingOnlyOnce");144 using (var browser2 = await Puppeteer.LaunchAsync(options, TestConstants.LoggerFactory))145 {146 var page2 = await browser2.NewPageAsync();147 await page2.GoToAsync(TestConstants.EmptyPage);148 Assert.Equal("doSomethingOnlyOnce=true", await page2.EvaluateExpressionAsync<string>("document.cookie"));149 }150 }151 }152 [Fact]153 public void ShouldReturnTheDefaultChromeArguments()154 {155 Assert.Contains("--no-first-run", Puppeteer.GetDefaultArgs());156 Assert.Contains("--headless", Puppeteer.GetDefaultArgs());157 Assert.DoesNotContain("--headless", Puppeteer.GetDefaultArgs(new LaunchOptions158 {159 Headless = false160 }));161 Assert.Contains("--user-data-dir=\"foo\"", Puppeteer.GetDefaultArgs(new LaunchOptions162 {163 UserDataDir = "foo"164 }));165 }166 [Fact]167 public async Task ChromeShouldBeClosed()168 {169 var options = TestConstants.DefaultBrowserOptions();170 var launcher = new Launcher(TestConstants.LoggerFactory);171 using (var browser = await launcher.LaunchAsync(options))172 using (var page = await browser.NewPageAsync())173 {174 var response = await page.GoToAsync(TestConstants.EmptyPage);175 Assert.Equal(HttpStatusCode.OK, response.Status);176 await browser.CloseAsync();177 Assert.True(launcher.Process.HasExited);178 }179 }180 [Fact]181 public async Task ChromeShouldBeClosedOnDispose()182 {183 var options = TestConstants.DefaultBrowserOptions();184 var launcher = new Launcher(TestConstants.LoggerFactory);185 using (var browser = await launcher.LaunchAsync(options))186 using (var page = await browser.NewPageAsync())187 {188 var response = await page.GoToAsync(TestConstants.EmptyPage);189 Assert.Equal(HttpStatusCode.OK, response.Status);190 }191 Assert.True(await launcher.Process.WaitForExitAsync(TimeSpan.FromSeconds(10)));192 Assert.True(launcher.Process.HasExited);193 }194 [Fact]195 public async Task ShouldNotOpenTwoChromesUsingTheSameLauncher()196 {197 var launcher = new Launcher(TestConstants.LoggerFactory);198 using (var browser = await launcher.LaunchAsync(TestConstants.DefaultBrowserOptions()))199 {200 var exception = await Assert.ThrowsAsync<InvalidOperationException>(() =>201 {202 return launcher.LaunchAsync(TestConstants.DefaultBrowserOptions());203 });204 Assert.Equal("Unable to create or connect to another chromium process", exception.Message);205 }206 }207 [Fact]208 public async Task ShouldWorkWithNoDefaultArguments()209 {210 var options = TestConstants.DefaultBrowserOptions();211 options.IgnoreDefaultArgs = true;212 using (var browser = await Puppeteer.LaunchAsync(options, TestConstants.LoggerFactory))213 using (var page = await browser.NewPageAsync())214 {215 Assert.Equal(121, await page.EvaluateExpressionAsync<int>("11 * 11"));216 }217 }218 [Fact]219 public async Task ShouldFilterOutIgnoredDefaultArguments()220 {221 var defaultArgs = Puppeteer.GetDefaultArgs();222 var options = TestConstants.DefaultBrowserOptions();223 options.IgnoredDefaultArgs = new[] { defaultArgs[0], defaultArgs[2] };224 using (var browser = await Puppeteer.LaunchAsync(options))225 {226 var spawnargs = browser.Process.StartInfo.Arguments;227 Assert.DoesNotContain(defaultArgs[0], spawnargs);228 Assert.Contains(defaultArgs[1], spawnargs);229 Assert.DoesNotContain(defaultArgs[2], spawnargs);230 }231 }232 [Fact]233 public async Task ShouldHaveDefaultUrlWhenLaunchingBrowser()234 {235 using (var browser = await Puppeteer.LaunchAsync(TestConstants.DefaultBrowserOptions(), TestConstants.LoggerFactory))236 {237 var pages = (await browser.PagesAsync()).Select(page => page.Url);238 Assert.Equal(new[] { TestConstants.AboutBlank }, pages);239 }240 }241 [Fact]242 public async Task ShouldHaveCustomUrlWhenLaunchingBrowser()243 {244 var options = TestConstants.DefaultBrowserOptions();245 options.Args = options.Args.Prepend(TestConstants.EmptyPage).ToArray();246 using (var browser = await Puppeteer.LaunchAsync(options, TestConstants.LoggerFactory))247 {248 var pages = await browser.PagesAsync();249 Assert.Single(pages);250 if (pages[0].Url != TestConstants.EmptyPage)251 {252 await pages[0].WaitForNavigationAsync();253 }254 Assert.Equal(TestConstants.EmptyPage, pages[0].Url);255 }256 }257 [Fact]258 public async Task ShouldSetTheDefaultViewport()259 {260 var options = TestConstants.DefaultBrowserOptions();261 options.DefaultViewport = new ViewPortOptions262 {263 Width = 456,264 Height = 789265 };266 using (var browser = await Puppeteer.LaunchAsync(options))267 using (var page = await browser.NewPageAsync())268 {269 Assert.Equal(456, await page.EvaluateExpressionAsync<int>("window.innerWidth"));270 Assert.Equal(789, await page.EvaluateExpressionAsync<int>("window.innerHeight"));271 }272 }273 [Fact]274 public async Task ShouldDisableTheDefaultViewport()275 {276 var options = TestConstants.DefaultBrowserOptions();277 options.DefaultViewport = null;278 using (var browser = await Puppeteer.LaunchAsync(options))279 using (var page = await browser.NewPageAsync())280 {281 Assert.Null(page.Viewport);282 }283 }284 [Fact]285 public async Task ShouldTakeFullPageScreenshotsWhenDefaultViewportIsNull()286 {287 var options = TestConstants.DefaultBrowserOptions();288 options.DefaultViewport = null;289 using (var browser = await Puppeteer.LaunchAsync(options))290 using (var page = await browser.NewPageAsync())291 {292 await page.GoToAsync(TestConstants.ServerUrl + "/grid.html");293 Assert.NotEmpty(await page.ScreenshotDataAsync(new ScreenshotOptions { FullPage = true }));294 }295 }296 [Fact]297 public async Task ShouldSupportCustomWebSocket()298 {299 var options = TestConstants.DefaultBrowserOptions();300 var customSocketCreated = false;301 options.WebSocketFactory = (uri, socketOptions, cancellationToken) =>302 {303 customSocketCreated = true;304 return WebSocketTransport.DefaultWebSocketFactory(uri, socketOptions, cancellationToken);305 };306 using (await Puppeteer.LaunchAsync(options, TestConstants.LoggerFactory))307 {308 Assert.True(customSocketCreated);309 }310 }311 [Fact]312 public async Task ShouldSupportCustomTransport()313 {314 var customTransportCreated = false;315 var options = TestConstants.DefaultBrowserOptions();316 options.TransportFactory = (url, opt, cancellationToken) =>317 {318 customTransportCreated = true;319 return WebSocketTransport.DefaultTransportFactory(url, opt, cancellationToken);320 };321 using (await Puppeteer.LaunchAsync(options, TestConstants.LoggerFactory))322 {323 Assert.True(customTransportCreated);324 }325 }326 }327}...

Full Screen

Full Screen

PuppeteerConnectTests.cs

Source:PuppeteerConnectTests.cs Github

copy

Full Screen

...39 [PuppeteerTest("launcher.spec.ts", "Puppeteer.connect", "should be able to close remote browser")]40 [PuppeteerFact]41 public async Task ShouldBeAbleToCloseRemoteBrowser()42 {43 var originalBrowser = await Puppeteer.LaunchAsync(TestConstants.DefaultBrowserOptions());44 var remoteBrowser = await Puppeteer.ConnectAsync(new ConnectOptions45 {46 BrowserWSEndpoint = originalBrowser.WebSocketEndpoint47 });48 var tcsDisconnected = new TaskCompletionSource<bool>();49 originalBrowser.Disconnected += (_, _) => tcsDisconnected.TrySetResult(true);50 await Task.WhenAll(51 tcsDisconnected.Task,52 remoteBrowser.CloseAsync());53 }54 [PuppeteerTest("launcher.spec.ts", "Puppeteer.connect", "should support ignoreHTTPSErrors option")]55 [PuppeteerFact]56 public async Task ShouldSupportIgnoreHTTPSErrorsOption()57 {58 await using (var originalBrowser = await Puppeteer.LaunchAsync(TestConstants.DefaultBrowserOptions()))59 await using (var browser = await Puppeteer.ConnectAsync(new ConnectOptions60 {61 BrowserWSEndpoint = originalBrowser.WebSocketEndpoint,62 IgnoreHTTPSErrors = true63 }))64 await using (var page = await browser.NewPageAsync())65 {66 var requestTask = HttpsServer.WaitForRequest(67 "/empty.html",68 request => request?.HttpContext?.Features?.Get<ITlsHandshakeFeature>()?.Protocol);69 var responseTask = page.GoToAsync(TestConstants.HttpsPrefix + "/empty.html");70 await Task.WhenAll(71 requestTask,72 responseTask).WithTimeout(Puppeteer.DefaultTimeout);73 var response = responseTask.Result;74 Assert.True(response.Ok);75 Assert.NotNull(response.SecurityDetails);76 Assert.Equal(77 TestUtils.CurateProtocol(requestTask.Result.ToString()),78 TestUtils.CurateProtocol(response.SecurityDetails.Protocol));79 }80 }81 [PuppeteerTest("launcher.spec.ts", "Puppeteer.connect", "should support targetFilter option")]82 [SkipBrowserFact(skipFirefox: true)]83 public async Task ShouldSupportTargetFilter()84 {85 await using (var originalBrowser = await Puppeteer.LaunchAsync(TestConstants.DefaultBrowserOptions()))86 {87 var page1 = await originalBrowser.NewPageAsync();88 await page1.GoToAsync(TestConstants.EmptyPage);89 var page2 = await originalBrowser.NewPageAsync();90 await page2.GoToAsync(TestConstants.EmptyPage + "?should-be-ignored");91 var browser = await Puppeteer.ConnectAsync(new ConnectOptions {92 BrowserWSEndpoint = originalBrowser.WebSocketEndpoint,93 TargetFilter = (TargetInfo targetInfo) => !targetInfo.Url.Contains("should-be-ignored"),94 });95 var pages = await browser.PagesAsync();96 await page2.CloseAsync();97 await page1.CloseAsync();98 await browser.CloseAsync();99 Assert.Equal(100 new string[]101 {102 "about:blank",103 TestConstants.EmptyPage104 },105 pages.Select((Page p) => p.Url).OrderBy(t => t));106 }107 }108 [PuppeteerFact]109 public async Task ShouldBeAbleToSetBrowserPropertiesUsingConnectOptions()110 {111 var initActionExecuted = false;112 var options = new ConnectOptions113 {114 BrowserWSEndpoint = Browser.WebSocketEndpoint,115 InitAction = brw =>116 {117 initActionExecuted = true;118 }119 };120 var browser = await Puppeteer.ConnectAsync(options, TestConstants.LoggerFactory);121 Assert.True(initActionExecuted);122 await browser.CloseAsync();123 }124 [PuppeteerTest("launcher.spec.ts", "Puppeteer.connect", "should be able to reconnect to a disconnected browser")]125 [SkipBrowserFact(skipFirefox: true)]126 public async Task ShouldBeAbleToReconnectToADisconnectedBrowser()127 {128 var options = new ConnectOptions()129 {130 BrowserWSEndpoint = Browser.WebSocketEndpoint131 };132 var url = TestConstants.ServerUrl + "/frames/nested-frames.html";133 var page = await Browser.NewPageAsync();134 await page.GoToAsync(url);135 Browser.Disconnect();136 await using (var browser = await Puppeteer.ConnectAsync(options, TestConstants.LoggerFactory))137 {138 var pages = (await browser.PagesAsync()).ToList();139 var restoredPage = pages.FirstOrDefault(x => x.Url == url);140 Assert.NotNull(restoredPage);141 var frameDump = FrameUtils.DumpFrames(restoredPage.MainFrame);142 Assert.Equal(TestConstants.NestedFramesDumpResult, frameDump);143 var response = await restoredPage.EvaluateExpressionAsync<int>("7 * 8");144 Assert.Equal(56, response);145 }146 }147 [PuppeteerTest("launcher.spec.ts", "Puppeteer.connect", "should be able to connect to the same page simultaneously")]148 [SkipBrowserFact(skipFirefox: true)]149 public async Task ShouldBeAbleToConnectToTheSamePageSimultaneously()150 {151 var browserOne = await Puppeteer.LaunchAsync(new LaunchOptions());152 var browserTwo = await Puppeteer.ConnectAsync(new ConnectOptions153 {154 BrowserWSEndpoint = browserOne.WebSocketEndpoint155 });156 var tcs = new TaskCompletionSource<Page>();157 async void TargetCreated(object sender, TargetChangedArgs e)158 {159 tcs.TrySetResult(await e.Target.PageAsync());160 browserOne.TargetCreated -= TargetCreated;161 }162 browserOne.TargetCreated += TargetCreated;163 var page2Task = browserTwo.NewPageAsync();164 await Task.WhenAll(tcs.Task, page2Task);165 var page1 = tcs.Task.Result;166 var page2 = page2Task.Result;167 Assert.Equal(56, await page1.EvaluateExpressionAsync<int>("7 * 8"));168 Assert.Equal(42, await page2.EvaluateExpressionAsync<int>("7 * 6"));169 await browserOne.CloseAsync();170 }171 [PuppeteerTest("launcher.spec.ts", "Puppeteer.connect", "should be able to reconnect")]172 [SkipBrowserFact(skipFirefox: true)]173 public async Task ShouldBeAbleToReconnect()174 {175 var browserOne = await Puppeteer.LaunchAsync(new LaunchOptions());176 var browserWSEndpoint = browserOne.WebSocketEndpoint;177 var page1 = await browserOne.NewPageAsync();178 await page1.GoToAsync(TestConstants.EmptyPage);179 browserOne.Disconnect();180 var browserTwo = await Puppeteer.ConnectAsync(new ConnectOptions181 {182 BrowserWSEndpoint = browserWSEndpoint183 });184 var pages = await browserTwo.PagesAsync();185 var pageTwo = pages.First(page => page.Url == TestConstants.EmptyPage);186 await pageTwo.ReloadAsync();187 var bodyHandle = await pageTwo.WaitForSelectorAsync("body", new WaitForSelectorOptions { Timeout = 10000 });188 await bodyHandle.DisposeAsync();189 await browserTwo.CloseAsync();...

Full Screen

Full Screen

HeadfulTests.cs

Source:HeadfulTests.cs Github

copy

Full Screen

...14 }15 [Fact]16 public async Task BackgroundPageTargetTypeShouldBeAvailable()17 {18 using (var browserWithExtension = await Puppeteer.LaunchAsync(19 TestConstants.BrowserWithExtensionOptions(),20 TestConstants.LoggerFactory))21 using (var page = await browserWithExtension.NewPageAsync())22 {23 var backgroundPageTarget = await browserWithExtension.WaitForTargetAsync(t => t.Type == TargetType.BackgroundPage);24 Assert.NotNull(backgroundPageTarget);25 }26 }27 [Fact]28 public async Task TargetPageShouldReturnABackgroundPage()29 {30 using (var browserWithExtension = await Puppeteer.LaunchAsync(31 TestConstants.BrowserWithExtensionOptions(),32 TestConstants.LoggerFactory))33 {34 var backgroundPageTarget = await browserWithExtension.WaitForTargetAsync(t => t.Type == TargetType.BackgroundPage);35 using (var page = await backgroundPageTarget.PageAsync())36 {37 Assert.Equal(6, await page.EvaluateFunctionAsync<int>("() => 2 * 3"));38 Assert.Equal(42, await page.EvaluateFunctionAsync<int>("() => window.MAGIC"));39 }40 }41 }42 [Fact]43 public async Task ShouldHaveDefaultUrlWhenLaunchingBrowser()44 {45 using (var browser = await Puppeteer.LaunchAsync(46 TestConstants.BrowserWithExtensionOptions(),47 TestConstants.LoggerFactory))48 {49 var pages = (await browser.PagesAsync()).Select(page => page.Url).ToArray();50 Assert.Equal(new[] { "about:blank" }, pages);51 }52 }53 [Fact]54 public async Task HeadlessShouldBeAbleToReadCookiesWrittenByHeadful()55 {56 using (var userDataDir = new TempDirectory())57 {58 var launcher = new Launcher(TestConstants.LoggerFactory);59 var options = TestConstants.DefaultBrowserOptions();60 options.Args = options.Args.Concat(new[] { $"--user-data-dir=\"{userDataDir}\"" }).ToArray();61 options.Headless = false;62 using (var browser = await launcher.LaunchAsync(options))63 using (var page = await browser.NewPageAsync())64 {65 await page.GoToAsync(TestConstants.EmptyPage);66 await page.EvaluateExpressionAsync(67 "document.cookie = 'foo=true; expires=Fri, 31 Dec 9999 23:59:59 GMT'");68 }69 await TestUtils.WaitForCookieInChromiumFileAsync(userDataDir.Path, "foo");70 options.Headless = true;71 using (var browser2 = await Puppeteer.LaunchAsync(options, TestConstants.LoggerFactory))72 {73 var page2 = await browser2.NewPageAsync();74 await page2.GoToAsync(TestConstants.EmptyPage);75 Assert.Equal("foo=true", await page2.EvaluateExpressionAsync<string>("document.cookie"));76 }77 }78 }79 [Fact(Skip = "TODO: Support OOOPIF. @see https://github.com/GoogleChrome/puppeteer/issues/2548")]80 public async Task OOPIFShouldReportGoogleComFrame()81 {82 // https://google.com is isolated by default in Chromium embedder.83 var headfulOptions = TestConstants.DefaultBrowserOptions();84 headfulOptions.Headless = false;85 using (var browser = await Puppeteer.LaunchAsync(headfulOptions))86 using (var page = await browser.NewPageAsync())87 {88 await page.GoToAsync(TestConstants.EmptyPage);89 await page.SetRequestInterceptionAsync(true);90 page.Request += async (sender, e) => await e.Request.RespondAsync(91 new ResponseData { Body = "{ body: 'YO, GOOGLE.COM'}" });92 await page.EvaluateFunctionHandleAsync(@"() => {93 const frame = document.createElement('iframe');94 frame.setAttribute('src', 'https://google.com/');95 document.body.appendChild(frame);96 return new Promise(x => frame.onload = x);97 }");98 await page.WaitForSelectorAsync("iframe[src=\"https://google.com/\"]");99 var urls = Array.ConvertAll(page.Frames, frame => frame.Url);100 Array.Sort(urls);101 Assert.Equal(new[] { TestConstants.EmptyPage, "https://google.com/" }, urls);102 }103 }104 [Fact]105 public async Task ShouldCloseBrowserWithBeforeunloadPage()106 {107 var headfulOptions = TestConstants.DefaultBrowserOptions();108 headfulOptions.Headless = false;109 using (var browser = await Puppeteer.LaunchAsync(headfulOptions))110 using (var page = await browser.NewPageAsync())111 {112 await page.GoToAsync(TestConstants.ServerUrl + "/beforeunload.html");113 // We have to interact with a page so that 'beforeunload' handlers fire.114 await page.ClickAsync("body");115 }116 }117 [Fact]118 public async Task ShouldOpenDevtoolsWhenDevtoolsTrueOptionIsGiven()119 {120 var headfulOptions = TestConstants.DefaultBrowserOptions();121 headfulOptions.Devtools = true;122 using (var browser = await Puppeteer.LaunchAsync(headfulOptions))123 {124 var context = await browser.CreateIncognitoBrowserContextAsync();125 await Task.WhenAll(126 context.NewPageAsync(),127 context.WaitForTargetAsync(target => target.Url.Contains("devtools://")));128 }129 }130 [Fact]131 public async Task BringToFrontShouldWork()132 {133 using (var browserWithExtension = await Puppeteer.LaunchAsync(134 TestConstants.BrowserWithExtensionOptions(),135 TestConstants.LoggerFactory))136 using (var page = await browserWithExtension.NewPageAsync())137 {138 await page.GoToAsync(TestConstants.EmptyPage);139 Assert.Equal("visible", await page.EvaluateExpressionAsync<string>("document.visibilityState"));140 var newPage = await browserWithExtension.NewPageAsync();141 await newPage.GoToAsync(TestConstants.EmptyPage);142 Assert.Equal("hidden", await page.EvaluateExpressionAsync<string>("document.visibilityState"));143 Assert.Equal("visible", await newPage.EvaluateExpressionAsync<string>("document.visibilityState"));144 await page.BringToFrontAsync();145 Assert.Equal("visible", await page.EvaluateExpressionAsync<string>("document.visibilityState"));146 Assert.Equal("hidden", await newPage.EvaluateExpressionAsync<string>("document.visibilityState"));147 await newPage.CloseAsync();...

Full Screen

Full Screen

Puppeteer.cs

Source:Puppeteer.cs Github

copy

Full Screen

...10 /// </summary>11 /// <example>12 /// The following is a typical example of using a Puppeteer to drive automation:13 /// <code>14 /// var browser = await Puppeteer.LaunchAsync(new LaunchOptions());15 /// var page = await browser.NewPageAsync();16 /// await page.GoToAsync("https://www.google.com");17 /// await Browser.CloseAsync();18 /// </code>19 /// </example>20 public static class Puppeteer21 {22 internal const int DefaultTimeout = 30_000;23 /// <summary>24 /// The default flags that Chromium will be launched with.25 /// </summary>26 public static string[] DefaultArgs => ChromiumProcess.DefaultArgs;27 /// <summary>28 /// A path where Puppeteer expects to find bundled Chromium. Chromium might not exist there if the downloader was not used.29 /// </summary>30 /// <returns>The path to chrome.exe</returns>31 public static string GetExecutablePath() => Launcher.GetExecutablePath();32 /// <summary>33 /// Returns an array of argument based on the options provided and the platform where the library is running 34 /// </summary>35 /// <returns>Chromium arguments.</returns>36 /// <param name="options">Options.</param>37 public static string[] GetDefaultArgs(LaunchOptions options = null)38 => ChromiumProcess.GetDefaultArgs(options ?? new LaunchOptions());39 /// <summary>40 /// The method launches a browser instance with given arguments. The browser will be closed when the Browser is disposed.41 /// </summary>42 /// <param name="options">Options for launching Chrome</param>43 /// <param name="loggerFactory">The logger factory</param>44 /// <returns>A connected browser.</returns>45 /// <remarks>46 /// See <a href="https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/">this article</a>47 /// for a description of the differences between Chromium and Chrome.48 /// <a href="https://chromium.googlesource.com/chromium/src/+/lkcr/docs/chromium_browser_vs_google_chrome.md">This article</a> describes some differences for Linux users.49 /// 50 /// Environment Variables51 /// Puppeteer looks for certain <see href="https://en.wikipedia.org/wiki/Environment_variable">environment variables</see>() to aid its operations.52 /// - <c>PUPPETEER_CHROMIUM_REVISION</c> - specify a certain version of Chromium you'd like Puppeteer to use. See <see cref="Puppeteer.LaunchAsync(LaunchOptions, ILoggerFactory)"/> on how executable path is inferred. 53 /// **BEWARE**: Puppeteer is only <see href="https://github.com/GoogleChrome/puppeteer/#q-why-doesnt-puppeteer-vxxx-work-with-chromium-vyyy">guaranteed to work</see> with the bundled Chromium, use at your own risk.54 /// - <c>PUPPETEER_EXECUTABLE_PATH</c> - specify an executable path to be used in <see cref="Puppeteer.LaunchAsync(LaunchOptions, ILoggerFactory)"/>. 55 /// **BEWARE**: Puppeteer is only <see href="https://github.com/GoogleChrome/puppeteer/#q-why-doesnt-puppeteer-vxxx-work-with-chromium-vyyy">guaranteed to work</see> with the bundled Chromium, use at your own risk.56 /// </remarks>57 public static Task<Browser> LaunchAsync(LaunchOptions options, ILoggerFactory loggerFactory = null)58 => new Launcher(loggerFactory).LaunchAsync(options);59 /// <summary>60 /// Attaches Puppeteer to an existing Chromium instance. The browser will be closed when the Browser is disposed.61 /// </summary>62 /// <param name="options">Options for connecting.</param>63 /// <param name="loggerFactory">The logger factory</param>64 /// <returns>A connected browser.</returns>65 public static Task<Browser> ConnectAsync(ConnectOptions options, ILoggerFactory loggerFactory = null)66 => new Launcher(loggerFactory).ConnectAsync(options);67 /// <summary>68 /// Creates the browser fetcher.69 /// </summary>70 /// <returns>The browser fetcher.</returns>71 /// <param name="options">Options.</param>72 public static BrowserFetcher CreateBrowserFetcher(BrowserFetcherOptions options)...

Full Screen

Full Screen

Program.cs

Source:Program.cs Github

copy

Full Screen

...12 static void Main(string[] args)13 {14 /*15 2020-02-17 Observation before introducing the killing of previous web browser processes:16 LaunchAsync failed if a process from the last run was still present.17 (See report of this issue at https://forum.botengine.org/t/farm-manager-tribal-wars-2-farmbot/3038/32?u=viir)18 Unhandled exception. System.AggregateException: One or more errors occurred. (Failed to launch Chromium! [28592:33396:0217/074915.470:ERROR:cache_util_win.cc(21)] Unable to move the cache: Access is denied. (0x5)19 [28592:33396:0217/074915.471:ERROR:cache_util.cc(141)] Unable to move cache folder C:\Users\John\AppData\Local\bot\web-browser\user-data\ShaderCache\GPUCache to C:\Users\John\AppData\Local\bot\web-browser\user-data\ShaderCache\old_GPUCache_00020 [28592:33396:0217/074915.471:ERROR:disk_cache.cc(178)] Unable to create cache21 [28592:33396:0217/074915.471:ERROR:shader_disk_cache.cc(601)] Shader Cache Creation failed: -222 [28592:33396:0217/074915.473:ERROR:browser_gpu_channel_host_factory.cc(138)] Failed to launch GPU process.23 )24 ---> PuppeteerSharp.ChromiumProcessException: Failed to launch Chromium! [28592:33396:0217/074915.470:ERROR:cache_util_win.cc(21)] Unable to move the cache: Access is denied. (0x5)25 [28592:33396:0217/074915.471:ERROR:cache_util.cc(141)] Unable to move cache folder C:\Users\John\AppData\Local\bot\web-browser\user-data\ShaderCache\GPUCache to C:\Users\John\AppData\Local\bot\web-browser\user-data\ShaderCache\old_GPUCache_00026 [28592:33396:0217/074915.471:ERROR:disk_cache.cc(178)] Unable to create cache27 [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();47 foreach (var process in matchingProcesses)48 {49 if (process.HasExited)50 continue;51 process.Kill();52 }53 }54 static bool ProcessIsWebBrowser(System.Diagnostics.Process process)55 {56 try57 {58 return process.MainModule.FileName.Contains(".local-chromium");59 }60 catch61 {62 return false;63 }64 }65 static async System.Threading.Tasks.Task StartWebBrowser()66 {67 await new PuppeteerSharp.BrowserFetcher().DownloadAsync(PuppeteerSharp.BrowserFetcher.DefaultRevision);68 browser = await PuppeteerSharp.Puppeteer.LaunchAsync(new PuppeteerSharp.LaunchOptions69 {70 Headless = false,71 UserDataDir = UserDataDirPath(),72 DefaultViewport = null,73 });74 browserPage = (await browser.PagesAsync()).FirstOrDefault() ?? await browser.NewPageAsync();75 await browserPage.ExposeFunctionAsync("____callback____", (string returnValue) =>76 {77 callbackFromBrowserDelegate?.Invoke(returnValue);78 return 0;79 });80 }81 }82}...

Full Screen

Full Screen

HeadlessChromiumPuppeteerLauncher.cs

Source:HeadlessChromiumPuppeteerLauncher.cs Github

copy

Full Screen

...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}...

Full Screen

Full Screen

HtmlToPdfConverter.cs

Source:HtmlToPdfConverter.cs Github

copy

Full Screen

...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,33 UseShellExecute = false,34 CreateNoWindow = true,35 }...

Full Screen

Full Screen

LaunchAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 {9 };10 var browser = await Puppeteer.LaunchAsync(options);11 var page = await browser.NewPageAsync();12 Console.ReadLine();13 }14 }15}16using System;17using System.Threading.Tasks;18using PuppeteerSharp;19{20 {21 static async Task Main(string[] args)22 {23 {24 };25 var browser = await Puppeteer.LaunchAsync(options);26 var page = await browser.NewPageAsync();27 Console.ReadLine();28 }29 }30}

Full Screen

Full Screen

LaunchAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 {9 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"10 };11 var browser = await Puppeteer.LaunchAsync(options);12 var page = await browser.NewPageAsync();13 await page.ScreenshotAsync("google.png");14 await browser.CloseAsync();15 }16 }17}18using System;19using System.Threading.Tasks;20using PuppeteerSharp;21{22 {23 static async Task Main(string[] args)24 {25 {26 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"27 };28 var browser = await Puppeteer.LaunchAsync(options);29 var page = await browser.NewPageAsync();30 await page.ScreenshotAsync("google.png");31 await browser.CloseAsync();32 }33 }34}35using System;36using System.Threading.Tasks;37using PuppeteerSharp;38{39 {40 static async Task Main(string[] args)41 {42 {43 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"44 };45 var browser = await Puppeteer.LaunchAsync(options);46 var page = await browser.NewPageAsync();47 await page.ScreenshotAsync("google.png");48 await browser.CloseAsync();49 }50 }51}

Full Screen

Full Screen

LaunchAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 {9 Args = new string[] { "--no-sandbox" }10 };11 var browser = await Puppeteer.LaunchAsync(options);12 var page = await browser.NewPageAsync();13 await page.ScreenshotAsync("google.png");14 await browser.CloseAsync();15 }16 }17}18using System;19using System.Threading.Tasks;20using PuppeteerSharp;21{22 {23 static async Task Main(string[] args)24 {25 {26 Args = new string[] { "--no-sandbox" }27 };28 var browser = await Puppeteer.LaunchAsync(options);29 var page = await browser.NewPageAsync();30 await page.ScreenshotAsync("google.png");31 await browser.CloseAsync();32 }33 }34}35using System;36using System.Threading.Tasks;37using PuppeteerSharp;38{39 {40 static async Task Main(string[] args)41 {42 {43 Args = new string[] { "--no-sandbox" }44 };45 var browser = await Puppeteer.LaunchAsync(options);46 var page = await browser.NewPageAsync();47 await page.ScreenshotAsync("google.png");48 await browser.CloseAsync();49 }50 }51}52using System;53using System.Threading.Tasks;54using PuppeteerSharp;55{56 {57 static async Task Main(string[] args)58 {59 {

Full Screen

Full Screen

LaunchAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 {9 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",10 Args = new[] { "--no-sandbox" }11 };12 using (var browser = await Puppeteer.LaunchAsync(options))13 {14 using (var page = await browser.NewPageAsync())15 {16 await page.ScreenshotAsync("google.png");17 }18 }19 }20 }21}

Full Screen

Full Screen

LaunchAsync

Using AI Code Generation

copy

Full Screen

1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3 Args = new string[] { "--no-sandbox" }4});5var page = await browser.NewPageAsync();6await page.ScreenshotAsync("google.png");7await browser.CloseAsync();8var browser = await Puppeteer.LaunchAsync(new LaunchOptions9{10 Args = new string[] { "--no-sandbox" }11});12var page = await browser.NewPageAsync();13await page.ScreenshotAsync("google.png");14await browser.CloseAsync();15var browser = await Puppeteer.LaunchAsync(new LaunchOptions16{17 Args = new string[] { "--no-sandbox" }18});19var page = await browser.NewPageAsync();20await page.ScreenshotAsync("google.png");21await browser.CloseAsync();22var browser = await Puppeteer.LaunchAsync(new LaunchOptions23{24 Args = new string[] { "--no-sandbox" }25});26var page = await browser.NewPageAsync();27await page.ScreenshotAsync("google.png");28await browser.CloseAsync();29var browser = await Puppeteer.LaunchAsync(new LaunchOptions30{31 Args = new string[] { "--no-sandbox" }32});33var page = await browser.NewPageAsync();34await page.ScreenshotAsync("google.png");35await browser.CloseAsync();36var browser = await Puppeteer.LaunchAsync(new LaunchOptions37{38 Args = new string[] { "--no-sandbox" }39});

Full Screen

Full Screen

LaunchAsync

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;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 PuppeteerSharp;20using System;21using System.Threading.Tasks;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}37using PuppeteerSharp;38using System;39using System.Threading.Tasks;40{41 {42 static async Task Main(string[] args)43 {44 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);45 var browser = await Puppeteer.LaunchAsync(new LaunchOptions46 {47 Args = new string[] { "--no-sandbox" }48 });49 var page = await browser.NewPageAsync();50 await page.ScreenshotAsync("google.png");51 await browser.CloseAsync();52 }53 }54}55using PuppeteerSharp;56using System;57using System.Threading.Tasks;58{59 {60 static async Task Main(string[]

Full Screen

Full Screen

LaunchAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args)7 {8 Run().GetAwaiter().GetResult();9 }10 static async Task Run()11 {12 {13 };14 var browser = await Puppeteer.LaunchAsync(options);15 var page = await browser.NewPageAsync();16 await page.PdfAsync("google.pdf");17 await browser.CloseAsync();18 }19 }20}21using System;22using System.Threading.Tasks;23using PuppeteerSharp;24{25 {26 static void Main(string[] args)27 {28 Run().GetAwaiter().GetResult();29 }30 static async Task Run()31 {32 {33 };34 var browser = await Puppeteer.LaunchAsync(options);35 var page = await browser.NewPageAsync();36 await page.ScreenshotAsync("google.png");37 await browser.CloseAsync();38 }39 }40}41using System;42using System.Threading.Tasks;43using PuppeteerSharp;44{45 {46 static void Main(string[] args)47 {48 Run().GetAwaiter().GetResult();49 }50 static async Task Run()51 {52 {53 };54 var browser = await Puppeteer.LaunchAsync(options);55 var page = await browser.NewPageAsync();56 await page.ScreenshotAsync("google.png");57 await page.PdfAsync("google.pdf");58 await browser.CloseAsync();59 }60 }61}62using System;63using System.Threading.Tasks;64using PuppeteerSharp;65{66 {

Full Screen

Full Screen

LaunchAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 });11 var page = await browser.NewPageAsync();12 await page.ScreenshotAsync("screenshot.png");13 await browser.CloseAsync();14 }15 }16}17using System;18using System.Threading.Tasks;19using PuppeteerSharp;20{21 {22 static void Main(string[] args)23 {24 var browser = Puppeteer.Launch(new LaunchOptions25 {26 }).Result;27 var page = browser.NewPageAsync().Result;28 page.ScreenshotAsync("screenshot.png").Wait();29 browser.CloseAsync().Wait();30 }31 }32}33using System;34using System.Threading.Tasks;35using PuppeteerSharp;36{37 {38 static async Task Main(string[] args)39 {40 var browser = await Puppeteer.LaunchAsync(new LaunchOptions41 {42 });43 var page = await browser.NewPageAsync();44 await page.ScreenshotAsync("screenshot.png");45 await browser.CloseAsync();46 }47 }48}49using System;50using System.Threading.Tasks;51using PuppeteerSharp;

Full Screen

Full Screen

LaunchAsync

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 Args = new[] { "--no-sandbox" }11 });12 var page = await browser.NewPageAsync();13 await page.ScreenshotAsync("google.png");14 await browser.CloseAsync();15 }16 }17}18using PuppeteerSharp;19using System;20using System.Threading.Tasks;21{22 {23 static async Task Main(string[] args)24 {25 var browser = await Puppeteer.LaunchAsync(new LaunchOptions26 {27 Args = new[] { "--no-sandbox" }28 });29 var page = await browser.NewPageAsync();30 await page.ScreenshotAsync("google.png");31 await browser.CloseAsync();32 }33 }34}35using PuppeteerSharp;36using System;37using System.Threading.Tasks;38{39 {40 static async Task Main(string[] args)41 {42 var browser = await Puppeteer.LaunchAsync(new LaunchOptions43 {44 Args = new[] { "--no-sandbox" }45 });46 var page = await browser.NewPageAsync();47 await page.ScreenshotAsync("google.png");48 await browser.CloseAsync();49 }50 }51}

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful