How to use WaitTask class of PuppeteerSharp package

Best Puppeteer-sharp code snippet using PuppeteerSharp.WaitTask

FrameWaitForSelectorTests.cs

Source:FrameWaitForSelectorTests.cs Github

copy

Full Screen

...3using PuppeteerSharp.Tests.Attributes;4using PuppeteerSharp.Xunit;5using Xunit;6using Xunit.Abstractions;7namespace PuppeteerSharp.Tests.WaitTaskTests8{9 [Collection(TestConstants.TestFixtureCollectionName)]10 public class FrameWaitForSelectorTests : PuppeteerPageBaseTest11 {12 const string AddElement = "tag => document.body.appendChild(document.createElement(tag))";13 public FrameWaitForSelectorTests(ITestOutputHelper output) : base(output)14 {15 }16 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should immediately resolve promise if node exists")]17 [PuppeteerFact]18 public async Task ShouldImmediatelyResolveTaskIfNodeExists()19 {20 await Page.GoToAsync(TestConstants.EmptyPage);21 var frame = Page.MainFrame;22 await frame.WaitForSelectorAsync("*");23 await frame.EvaluateFunctionAsync(AddElement, "div");24 await frame.WaitForSelectorAsync("div");25 }26 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should work with removed MutationObserver")]27 [SkipBrowserFact(skipFirefox: true)]28 public async Task ShouldWorkWithRemovedMutationObserver()29 {30 await Page.EvaluateExpressionAsync("delete window.MutationObserver");31 var waitForSelector = Page.WaitForSelectorAsync(".zombo");32 await Task.WhenAll(33 waitForSelector,34 Page.SetContentAsync("<div class='zombo'>anything</div>"));35 Assert.Equal("anything", await Page.EvaluateFunctionAsync<string>("x => x.textContent", await waitForSelector));36 }37 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should resolve promise when node is added")]38 [PuppeteerFact]39 public async Task ShouldResolveTaskWhenNodeIsAdded()40 {41 await Page.GoToAsync(TestConstants.EmptyPage);42 var frame = Page.MainFrame;43 var watchdog = frame.WaitForSelectorAsync("div");44 await frame.EvaluateFunctionAsync(AddElement, "br");45 await frame.EvaluateFunctionAsync(AddElement, "div");46 var eHandle = await watchdog;47 var property = await eHandle.GetPropertyAsync("tagName");48 var tagName = await property.JsonValueAsync<string>();49 Assert.Equal("DIV", tagName);50 }51 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should work when node is added through innerHTML")]52 [PuppeteerFact]53 public async Task ShouldWorkWhenNodeIsAddedThroughInnerHTML()54 {55 await Page.GoToAsync(TestConstants.EmptyPage);56 var watchdog = Page.WaitForSelectorAsync("h3 div");57 await Page.EvaluateFunctionAsync(AddElement, "span");58 await Page.EvaluateExpressionAsync("document.querySelector('span').innerHTML = '<h3><div></div></h3>'");59 await watchdog;60 }61 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "Page.waitForSelector is shortcut for main frame")]62 [PuppeteerFact]63 public async Task PageWaitForSelectorAsyncIsShortcutForMainFrame()64 {65 await Page.GoToAsync(TestConstants.EmptyPage);66 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);67 var otherFrame = Page.FirstChildFrame();68 var watchdog = Page.WaitForSelectorAsync("div");69 await otherFrame.EvaluateFunctionAsync(AddElement, "div");70 await Page.EvaluateFunctionAsync(AddElement, "div");71 var eHandle = await watchdog;72 Assert.Equal(Page.MainFrame, eHandle.ExecutionContext.Frame);73 }74 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should run in specified frame")]75 [PuppeteerFact]76 public async Task ShouldRunInSpecifiedFrame()77 {78 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);79 await FrameUtils.AttachFrameAsync(Page, "frame2", TestConstants.EmptyPage);80 var frame1 = Page.FirstChildFrame();81 var frame2 = Page.Frames.ElementAt(2);82 var waitForSelectorPromise = frame2.WaitForSelectorAsync("div");83 await frame1.EvaluateFunctionAsync(AddElement, "div");84 await frame2.EvaluateFunctionAsync(AddElement, "div");85 var eHandle = await waitForSelectorPromise;86 Assert.Equal(frame2, eHandle.ExecutionContext.Frame);87 }88 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should throw when frame is detached")]89 [SkipBrowserFact(skipFirefox: true)]90 public async Task ShouldThrowWhenFrameIsDetached()91 {92 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);93 var frame = Page.FirstChildFrame();94 var waitTask = frame.WaitForSelectorAsync(".box").ContinueWith(task => task?.Exception?.InnerException);95 await FrameUtils.DetachFrameAsync(Page, "frame1");96 var waitException = await waitTask;97 Assert.NotNull(waitException);98 Assert.Contains("waitForFunction failed: frame got detached.", waitException.Message);99 }100 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should survive cross-process navigation")]101 [PuppeteerFact]102 public async Task ShouldSurviveCrossProcessNavigation()103 {104 var boxFound = false;105 var waitForSelector = Page.WaitForSelectorAsync(".box").ContinueWith(_ => boxFound = true);106 await Page.GoToAsync(TestConstants.EmptyPage);107 Assert.False(boxFound);108 await Page.ReloadAsync();109 Assert.False(boxFound);110 await Page.GoToAsync(TestConstants.CrossProcessHttpPrefix + "/grid.html");111 await waitForSelector;112 Assert.True(boxFound);113 }114 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should wait for visible")]115 [PuppeteerFact]116 public async Task ShouldWaitForVisible()117 {118 var divFound = false;119 var waitForSelector = Page.WaitForSelectorAsync("div", new WaitForSelectorOptions { Visible = true })120 .ContinueWith(_ => divFound = true);121 await Page.SetContentAsync("<div style='display: none; visibility: hidden;'>1</div>");122 Assert.False(divFound);123 await Page.EvaluateExpressionAsync("document.querySelector('div').style.removeProperty('display')");124 Assert.False(divFound);125 await Page.EvaluateExpressionAsync("document.querySelector('div').style.removeProperty('visibility')");126 Assert.True(await waitForSelector);127 Assert.True(divFound);128 }129 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should wait for visible recursively")]130 [PuppeteerFact]131 public async Task ShouldWaitForVisibleRecursively()132 {133 var divVisible = false;134 var waitForSelector = Page.WaitForSelectorAsync("div#inner", new WaitForSelectorOptions { Visible = true })135 .ContinueWith(_ => divVisible = true);136 await Page.SetContentAsync("<div style='display: none; visibility: hidden;'><div id='inner'>hi</div></div>");137 Assert.False(divVisible);138 await Page.EvaluateExpressionAsync("document.querySelector('div').style.removeProperty('display')");139 Assert.False(divVisible);140 await Page.EvaluateExpressionAsync("document.querySelector('div').style.removeProperty('visibility')");141 Assert.True(await waitForSelector);142 Assert.True(divVisible);143 }144 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "hidden should wait for visibility: hidden")]145 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "hidden should wait for display: none")]146 [Theory]147 [InlineData("visibility", "hidden")]148 [InlineData("display", "none")]149 public async Task HiddenShouldWaitForVisibility(string propertyName, string propertyValue)150 {151 var divHidden = false;152 await Page.SetContentAsync("<div style='display: block;'></div>");153 var waitForSelector = Page.WaitForSelectorAsync("div", new WaitForSelectorOptions { Hidden = true })154 .ContinueWith(_ => divHidden = true);155 await Page.WaitForSelectorAsync("div"); // do a round trip156 Assert.False(divHidden);157 await Page.EvaluateExpressionAsync($"document.querySelector('div').style.setProperty('{propertyName}', '{propertyValue}')");158 Assert.True(await waitForSelector);159 Assert.True(divHidden);160 }161 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "hidden should wait for removal")]162 [PuppeteerFact]163 public async Task HiddenShouldWaitForRemoval()164 {165 await Page.SetContentAsync("<div></div>");166 var divRemoved = false;167 var waitForSelector = Page.WaitForSelectorAsync("div", new WaitForSelectorOptions { Hidden = true })168 .ContinueWith(_ => divRemoved = true);169 await Page.WaitForSelectorAsync("div"); // do a round trip170 Assert.False(divRemoved);171 await Page.EvaluateExpressionAsync("document.querySelector('div').remove()");172 Assert.True(await waitForSelector);173 Assert.True(divRemoved);174 }175 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should return null if waiting to hide non-existing element")]176 [PuppeteerFact]177 public async Task ShouldReturnNullIfWaitingToHideNonExistingElement()178 {179 var handle = await Page.WaitForSelectorAsync("non-existing", new WaitForSelectorOptions { Hidden = true });180 Assert.Null(handle);181 }182 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should respect timeout")]183 [PuppeteerFact]184 public async Task ShouldRespectTimeout()185 {186 var exception = await Assert.ThrowsAsync<WaitTaskTimeoutException>(async ()187 => await Page.WaitForSelectorAsync("div", new WaitForSelectorOptions { Timeout = 10 }));188 Assert.Contains("waiting for selector 'div' failed: timeout", exception.Message);189 }190 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should have an error message specifically for awaiting an element to be hidden")]191 [PuppeteerFact]192 public async Task ShouldHaveAnErrorMessageSpecificallyForAwaitingAnElementToBeHidden()193 {194 await Page.SetContentAsync("<div></div>");195 var exception = await Assert.ThrowsAsync<WaitTaskTimeoutException>(async ()196 => await Page.WaitForSelectorAsync("div", new WaitForSelectorOptions { Hidden = true, Timeout = 10 }));197 Assert.Contains("waiting for selector 'div' to be hidden failed: timeout", exception.Message);198 }199 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should respond to node attribute mutation")]200 [PuppeteerFact]201 public async Task ShouldRespondToNodeAttributeMutation()202 {203 var divFound = false;204 var waitForSelector = Page.WaitForSelectorAsync(".zombo").ContinueWith(_ => divFound = true);205 await Page.SetContentAsync("<div class='notZombo'></div>");206 Assert.False(divFound);207 await Page.EvaluateExpressionAsync("document.querySelector('div').className = 'zombo'");208 Assert.True(await waitForSelector);209 }210 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should return the element handle")]211 [PuppeteerFact]212 public async Task ShouldReturnTheElementHandle()213 {214 var waitForSelector = Page.WaitForSelectorAsync(".zombo");215 await Page.SetContentAsync("<div class='zombo'>anything</div>");216 Assert.Equal("anything", await Page.EvaluateFunctionAsync<string>("x => x.textContent", await waitForSelector));217 }218 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should have correct stack trace for timeout")]219 [PuppeteerFact]220 public async Task ShouldHaveCorrectStackTraceForTimeout()221 {222 var exception = await Assert.ThrowsAsync<WaitTaskTimeoutException>(async ()223 => await Page.WaitForSelectorAsync(".zombo", new WaitForSelectorOptions { Timeout = 10 }));224 Assert.Contains("WaitForSelectorTests", exception.StackTrace);225 }226 }227}...

Full Screen

Full Screen

PdfService.cs

Source:PdfService.cs Github

copy

Full Screen

1using System;2using System.Linq;3using System.IO;4using System.Threading.Tasks;5using Microsoft.Extensions.Configuration;6using PuppeteerSharp;7using PuppeteerSharp.Media;8using Microsoft.Extensions.Logging;910namespace Zbyrach.Pdf11{12 public class PdfService13 {14 private const int PDF_GENERATION_TIMEOUT = 60000;15 private readonly string _chromiumExecutablePath;16 private readonly ILogger<PdfService> _logger;1718 public PdfService(IConfiguration configuration, ILogger<PdfService> logger)19 {20 _chromiumExecutablePath = configuration["PUPPETEER_EXECUTABLE_PATH"];21 _logger = logger;22 }2324 public async Task<Stream> ConvertUrlToPdf(string url, DeviceType deviceType, bool inline = false)25 {26 Stream result = null;27 await ConvertUrlToPdf(url, new DeviceType[] { deviceType }, new bool[] { inline }, async (device, inln, stream) =>28 {29 result = stream;30 });31 return result;32 }3334 public async Task ConvertUrlToPdf(string url, DeviceType[] deviceTypes, bool[] inlines, Func<DeviceType, bool, Stream, Task> callback)35 {36 inlines = inlines37 .OrderByDescending(i => i)38 .ToArray();3940 var options = new LaunchOptions41 {42 Headless = true,43 Args = new[]44 {45 "--no-sandbox",46 "--disable-plugins",47 "--incognito",48 "--disable-sync",49 "--disable-gpu",50 "--disable-speech-api",51 "--disable-remote-fonts",52 "--disable-shared-workers",53 "--disable-webgl",54 "--no-experiments",55 "--no-first-run",56 "--no-default-browser-check",57 "--no-wifi",58 "--no-pings",59 "--no-service-autorun",60 "--disable-databases",61 "--disable-default-apps",62 "--disable-demo-mode",63 "--disable-notifications",64 "--disable-permissions-api",65 "--disable-background-networking",66 "--disable-3d-apis",67 "--disable-bundled-ppapi-flash",68 },69 ExecutablePath = _chromiumExecutablePath,70 Timeout = PDF_GENERATION_TIMEOUT71 };7273 using var browser = await Puppeteer.LaunchAsync(options);74 using var page = await browser.NewPageAsync();7576 await page.GoToAsync(url);7778 await RemoveRedundantContent(page);79 await ScrollPageToBottom(page);80 await RemoveTopBanner(page);81 await RemoveFreeStoriesLeftBanner(page);82 await RemoveFollowLinks(page);8384 foreach (var inline in inlines)85 {86 foreach (var deviceType in deviceTypes)87 {88 if (!inline)89 {90 await RemovePageBreaks(page);91 }9293 var format = deviceType switch94 {95 DeviceType.Mobile => PaperFormat.A6,96 DeviceType.Tablet => inline ? PaperFormat.A4 : PaperFormat.A5,97 DeviceType.Desktop => PaperFormat.A4,98 _ => throw new ArgumentOutOfRangeException(nameof(deviceType))99 };100101 var stream = await page.PdfStreamAsync(new PdfOptions102 {103 Format = format,104 MarginOptions = new PuppeteerSharp.Media.MarginOptions105 {106 Top = inline ? "0px" : "40px",107 Bottom = inline ? "0px" : "40px"108 }109 });110111 await callback(deviceType, inline, stream);112 }113 }114 }115116 private async Task RemovePageBreaks(Page page)117 {118 var markerString = Guid.NewGuid().ToString();119 await ExecuteJavascript(page, @"()=> {120 var style = document.createElement('style');121 style.innerHTML = `122 h1, h2 {123 page-break-inside: avoid;124 }125 h1::after, h2::after {126 content: '';127 display: block;128 height: 100px;129 margin-bottom: -100px;130 }131 .paragraph-image, figure {132 page-break-inside: avoid;133 page-break-before: auto;134 page-break-after: auto;135 }136 `;137 document.head.appendChild(style); 138 console.log('" + markerString + @"'); 139 }", markerString);140 _logger.LogInformation("Page breaks were removed.");141 }142143 private async Task RemoveFollowLinks(Page page)144 {145 var markerString = Guid.NewGuid().ToString();146 await ExecuteJavascript(page, @"()=> {147 const links = document.querySelectorAll('a, button');148 for (let link of links) {149 if (link.textContent.includes('Follow')) {150 link.style.display = 'none';151 }152 if (link.getAttribute('target') !== '_blank') {153 link.removeAttribute('href'); 154 } 155 }156 console.log('" + markerString + @"'); 157 }", markerString);158 _logger.LogInformation("Follow links were removed.");159 }160161 private async Task RemoveFreeStoriesLeftBanner(Page page)162 {163 var markerString = Guid.NewGuid().ToString();164 await ExecuteJavascript(page, @"()=> {165 var xpath = ""//span[contains(.,'member-only stor')]"";166 var banner = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; 167 if (banner && banner.textContent.includes('stories left this month.')) {168 var parent = banner.parentElement;169 while (parent) {170 if (parent.parentElement.nodeName == 'ARTICLE') {171 break;172 }173 parent = parent.parentElement;174 } 175 parent.parentElement.removeChild(parent); 176 }177 console.log('" + markerString + @"'); 178 }", markerString);179 _logger.LogInformation("The free stories banner was removed.");180 }181182 private async Task RemoveTopBanner(Page page)183 {184 var markerString = Guid.NewGuid().ToString();185 await ExecuteJavascript(page, @"()=> {186 var banner = document.querySelector('.branch-journeys-top');187 if (banner) {188 var parent = banner.parentElement;189 while (parent) {190 if (parent.parentElement == document.body) {191 break;192 }193 parent = parent.parentElement;194 } 195 document.body.removeChild(parent);196 } 197 console.log('" + markerString + @"'); 198 }", markerString);199 _logger.LogInformation("The top banner was removed.");200 }201202 private async Task ScrollPageToBottom(Page page)203 {204 var markerString = Guid.NewGuid().ToString();205 await ExecuteJavascript(page, @"()=> { 206 var currentScroll = 0;207 var scrollStep = 200;208 var scrollInterval = 100;209210 function scrool() {211 if (currentScroll > document.body.scrollHeight) {212 console.log('" + markerString + @"'); 213 return;214 }215 currentScroll += scrollStep;216 window.scrollBy(0, scrollStep); 217 setTimeout(scrool, scrollInterval);218 };219 220 scrool(); 221 }", markerString);222 _logger.LogInformation("Scrolling to the bottom was finished.");223 }224225 private async Task RemoveRedundantContent(Page page)226 {227 var markerString = Guid.NewGuid().ToString();228 await ExecuteJavascript(page, @"()=> {229 const article = document.querySelectorAll('article')[0];230 if (article) {231 const parent = article.parentNode;232 parent.innerHTML = '';233 parent.append(article);234 } 235 console.log('" + markerString + @"'); 236 }", markerString);237 _logger.LogInformation("Redundant content was removed.");238 }239240 private async Task ExecuteJavascript(Page page, string javaScript, string markerString)241 {242 if (string.IsNullOrEmpty(markerString))243 {244 throw new Exception("Marker string can not be empty.");245 }246247 var lastLogMessage = string.Empty;248249 async void ConsoleHandler(object sender, ConsoleEventArgs args)250 {251 switch (args.Message.Type)252 {253 case ConsoleType.Error:254 try255 {256 var errorArgs = await Task.WhenAll(args.Message.Args.Select(257 arg => arg.ExecutionContext.EvaluateFunctionAsync("(arg) => arg instanceof Error ? arg.message : arg", arg)));258 _logger.LogError($"{args.Message.Text} args: [{string.Join<object>(", ", errorArgs)}]");259 }260 catch { }261 break;262 case ConsoleType.Warning:263 _logger.LogWarning(args.Message.Text);264 break;265 default:266 lastLogMessage = args.Message.Text;267 break;268 }269 };270271 page.Console += ConsoleHandler;272 try273 {274 await page.EvaluateFunctionAsync(javaScript);275 await WaitUntil(() => lastLogMessage == markerString);276 }277 finally278 {279 page.Console -= ConsoleHandler;280 }281 }282 private async Task WaitUntil(Func<bool> condition, int frequency = 100, int timeout = PDF_GENERATION_TIMEOUT)283 {284 var waitTask = Task.Run(async () =>285 {286 while (!condition())287 {288 await Task.Delay(frequency);289 }290 });291292 if (waitTask != await Task.WhenAny(waitTask,293 Task.Delay(timeout)))294 throw new TimeoutException();295 }296 } ...

Full Screen

Full Screen

FrameWaitForFunctionTests.cs

Source:FrameWaitForFunctionTests.cs Github

copy

Full Screen

...3using PuppeteerSharp.Tests.Attributes;4using PuppeteerSharp.Xunit;5using Xunit;6using Xunit.Abstractions;7namespace PuppeteerSharp.Tests.WaitTaskTests8{9 [Collection(TestConstants.TestFixtureCollectionName)]10 public class FrameWaitForFunctionTests : PuppeteerPageBaseTest11 {12 public FrameWaitForFunctionTests(ITestOutputHelper output) : base(output)13 {14 }15 [PuppeteerTest("waittask.spec.ts", "Frame.waitForFunction", "should work when resolved right before execution context disposal")]16 [PuppeteerFact]17 public async Task ShouldWorkWhenResolvedRightBeforeExecutionContextDisposal()18 {19 await Page.EvaluateFunctionOnNewDocumentAsync("() => window.__RELOADED = true");20 await Page.WaitForFunctionAsync(@"() =>21 {22 if (!window.__RELOADED)23 window.location.reload();24 return true;25 }");26 }27 [PuppeteerTest("waittask.spec.ts", "Frame.waitForFunction", "should poll on interval")]28 [PuppeteerFact]29 public async Task ShouldPollOnInterval()30 {31 var success = false;32 var startTime = DateTime.Now;33 var polling = 100;34 var watchdog = Page.WaitForFunctionAsync("() => window.__FOO === 'hit'", new WaitForFunctionOptions { PollingInterval = polling })35 .ContinueWith(_ => success = true);36 await Page.EvaluateExpressionAsync("window.__FOO = 'hit'");37 Assert.False(success);38 await Page.EvaluateExpressionAsync("document.body.appendChild(document.createElement('div'))");39 await watchdog;40 Assert.True((DateTime.Now - startTime).TotalMilliseconds > polling / 2);41 }42 43 [PuppeteerTest("waittask.spec.ts", "Frame.waitForFunction", "should poll on interval async")]44 [PuppeteerFact]45 public async Task ShouldPollOnIntervalAsync()46 {47 var success = false;48 var startTime = DateTime.Now;49 var polling = 100;50 var watchdog = Page.WaitForFunctionAsync("async () => window.__FOO === 'hit'", new WaitForFunctionOptions { PollingInterval = polling })51 .ContinueWith(_ => success = true);52 await Page.EvaluateFunctionAsync("async () => window.__FOO = 'hit'");53 Assert.False(success);54 await Page.EvaluateExpressionAsync("document.body.appendChild(document.createElement('div'))");55 await watchdog;56 Assert.True((DateTime.Now - startTime).TotalMilliseconds > polling / 2);57 }58 [PuppeteerTest("waittask.spec.ts", "Frame.waitForFunction", "should poll on mutation")]59 [PuppeteerFact]60 public async Task ShouldPollOnMutation()61 {62 var success = false;63 var watchdog = Page.WaitForFunctionAsync("() => window.__FOO === 'hit'",64 new WaitForFunctionOptions { Polling = WaitForFunctionPollingOption.Mutation })65 .ContinueWith(_ => success = true);66 await Page.EvaluateExpressionAsync("window.__FOO = 'hit'");67 Assert.False(success);68 await Page.EvaluateExpressionAsync("document.body.appendChild(document.createElement('div'))");69 await watchdog;70 }71 [PuppeteerTest("waittask.spec.ts", "Frame.waitForFunction", "should poll on mutation async")]72 [PuppeteerFact]73 public async Task ShouldPollOnMutationAsync()74 {75 var success = false;76 var watchdog = Page.WaitForFunctionAsync("async () => window.__FOO === 'hit'",77 new WaitForFunctionOptions { Polling = WaitForFunctionPollingOption.Mutation })78 .ContinueWith(_ => success = true);79 await Page.EvaluateFunctionAsync("async () => window.__FOO = 'hit'");80 Assert.False(success);81 await Page.EvaluateExpressionAsync("document.body.appendChild(document.createElement('div'))");82 await watchdog;83 }84 [PuppeteerTest("waittask.spec.ts", "Frame.waitForFunction", "should poll on raf")]85 [PuppeteerFact]86 public async Task ShouldPollOnRaf()87 {88 var watchdog = Page.WaitForFunctionAsync("() => window.__FOO === 'hit'",89 new WaitForFunctionOptions { Polling = WaitForFunctionPollingOption.Raf });90 await Page.EvaluateExpressionAsync("window.__FOO = 'hit'");91 await watchdog;92 }93 [PuppeteerTest("waittask.spec.ts", "Frame.waitForFunction", "should poll on raf async")]94 [PuppeteerFact]95 public async Task ShouldPollOnRafAsync()96 {97 var watchdog = Page.WaitForFunctionAsync("async () => window.__FOO === 'hit'",98 new WaitForFunctionOptions { Polling = WaitForFunctionPollingOption.Raf });99 await Page.EvaluateFunctionAsync("async () => (globalThis.__FOO = 'hit')");100 await watchdog;101 }102 [PuppeteerTest("waittask.spec.ts", "Frame.waitForFunction", "should work with strict CSP policy")]103 [SkipBrowserFact(skipFirefox: true)]104 public async Task ShouldWorkWithStrictCSPPolicy()105 {106 Server.SetCSP("/empty.html", "script-src " + TestConstants.ServerUrl);107 await Page.GoToAsync(TestConstants.EmptyPage);108 await Task.WhenAll(109 Page.WaitForFunctionAsync("() => window.__FOO === 'hit'", new WaitForFunctionOptions110 {111 Polling = WaitForFunctionPollingOption.Raf112 }),113 Page.EvaluateExpressionAsync("window.__FOO = 'hit'"));114 }115 [PuppeteerTest("waittask.spec.ts", "Frame.waitForFunction", "should throw negative polling interval")]116 [PuppeteerFact]117 public async Task ShouldThrowNegativePollingInterval()118 {119 var exception = await Assert.ThrowsAsync<ArgumentOutOfRangeException>(()120 => Page.WaitForFunctionAsync("() => !!document.body", new WaitForFunctionOptions { PollingInterval = -10 }));121 Assert.Contains("Cannot poll with non-positive interval", exception.Message);122 }123 [PuppeteerTest("waittask.spec.ts", "Frame.waitForFunction", "should return the success value as a JSHandle")]124 [PuppeteerFact]125 public async Task ShouldReturnTheSuccessValueAsAJSHandle()126 => Assert.Equal(5, await (await Page.WaitForFunctionAsync("() => 5")).JsonValueAsync<int>());127 [PuppeteerTest("waittask.spec.ts", "Frame.waitForFunction", "should return the window as a success value")]128 [PuppeteerFact]129 public async Task ShouldReturnTheWindowAsASuccessValue()130 => Assert.NotNull(await Page.WaitForFunctionAsync("() => window"));131 [PuppeteerTest("waittask.spec.ts", "Frame.waitForFunction", "should accept ElementHandle arguments")]132 [PuppeteerFact]133 public async Task ShouldAcceptElementHandleArguments()134 {135 await Page.SetContentAsync("<div></div>");136 var div = await Page.QuerySelectorAsync("div");137 var resolved = false;138 var waitForFunction = Page.WaitForFunctionAsync("element => !element.parentElement", div)139 .ContinueWith(_ => resolved = true);140 Assert.False(resolved);141 await Page.EvaluateFunctionAsync("element => element.remove()", div);142 await waitForFunction;143 }144 [PuppeteerTest("waittask.spec.ts", "Frame.waitForFunction", "should respect timeout")]145 [PuppeteerFact]146 public async Task ShouldRespectTimeout()147 {148 var exception = await Assert.ThrowsAsync<WaitTaskTimeoutException>(()149 => Page.WaitForExpressionAsync("false", new WaitForFunctionOptions { Timeout = 10 }));150 Assert.Contains("waiting for function failed: timeout", exception.Message);151 }152 [PuppeteerTest("waittask.spec.ts", "Frame.waitForFunction", "should respect default timeout")]153 [PuppeteerFact]154 public async Task ShouldRespectDefaultTimeout()155 {156 Page.DefaultTimeout = 1;157 var exception = await Assert.ThrowsAsync<WaitTaskTimeoutException>(()158 => Page.WaitForExpressionAsync("false"));159 Assert.Contains("waiting for function failed: timeout", exception.Message);160 }161 [PuppeteerTest("waittask.spec.ts", "Frame.waitForFunction", "should disable timeout when its set to 0")]162 [PuppeteerFact]163 public async Task ShouldDisableTimeoutWhenItsSetTo0()164 {165 var watchdog = Page.WaitForFunctionAsync(@"() => {166 window.__counter = (window.__counter || 0) + 1;167 return window.__injected;168 }", new WaitForFunctionOptions { Timeout = 0, PollingInterval = 10 });169 await Page.WaitForFunctionAsync("() => window.__counter > 10");170 await Page.EvaluateExpressionAsync("window.__injected = true");171 await watchdog;...

Full Screen

Full Screen

FrameWaitForXPathTests.cs

Source:FrameWaitForXPathTests.cs Github

copy

Full Screen

...5using Xunit.Abstractions;6using PuppeteerSharp.Helpers;7using PuppeteerSharp.Xunit;8using PuppeteerSharp.Tests.Attributes;9namespace PuppeteerSharp.Tests.WaitTaskTests10{11 [Collection(TestConstants.TestFixtureCollectionName)]12 public class FrameWaitForXPathTests : PuppeteerPageBaseTest13 {14 const string addElement = "tag => document.body.appendChild(document.createElement(tag))";15 public FrameWaitForXPathTests(ITestOutputHelper output) : base(output)16 {17 }18 [PuppeteerTest("waittask.spec.ts", "Frame.waitForXPath", "should support some fancy xpath")]19 [PuppeteerFact]20 public async Task ShouldSupportSomeFancyXpath()21 {22 await Page.SetContentAsync("<p>red herring</p><p>hello world </p>");23 var waitForXPath = Page.WaitForXPathAsync("//p[normalize-space(.)=\"hello world\"]");24 Assert.Equal("hello world ", await Page.EvaluateFunctionAsync<string>("x => x.textContent", await waitForXPath));25 }26 [PuppeteerTest("waittask.spec.ts", "Frame.waitForXPath", "should run in specified frame")]27 [PuppeteerFact]28 public async Task ShouldRunInSpecifiedFrame()29 {30 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);31 await FrameUtils.AttachFrameAsync(Page, "frame2", TestConstants.EmptyPage);32 var frame1 = Page.Frames.First(f => f.Name == "frame1");33 var frame2 = Page.Frames.First(f => f.Name == "frame2");34 var waitForXPathPromise = frame2.WaitForXPathAsync("//div");35 await frame1.EvaluateFunctionAsync(addElement, "div");36 await frame2.EvaluateFunctionAsync(addElement, "div");37 var eHandle = await waitForXPathPromise;38 Assert.Equal(frame2, eHandle.ExecutionContext.Frame);39 }40 [PuppeteerTest("waittask.spec.ts", "Frame.waitForXPath", "should throw when frame is detached")]41 [SkipBrowserFact(skipFirefox: true)]42 public async Task ShouldThrowWhenFrameIsDetached()43 {44 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);45 var frame = Page.FirstChildFrame();46 var waitPromise = frame.WaitForXPathAsync("//*[@class=\"box\"]");47 await FrameUtils.DetachFrameAsync(Page, "frame1");48 var exception = await Assert.ThrowsAnyAsync<Exception>(() => waitPromise);49 Assert.Contains("waitForFunction failed: frame got detached.", exception.Message);50 }51 [PuppeteerTest("waittask.spec.ts", "Frame.waitForXPath", "hidden should wait for display: none")]52 [PuppeteerFact]53 public async Task HiddenShouldWaitForDisplayNone()54 {55 var divHidden = false;56 await Page.SetContentAsync("<div style='display: block;'></div>");57 var waitForXPath = Page.WaitForXPathAsync("//div", new WaitForSelectorOptions { Hidden = true })58 .ContinueWith(_ => divHidden = true);59 await Page.WaitForXPathAsync("//div"); // do a round trip60 Assert.False(divHidden);61 await Page.EvaluateExpressionAsync("document.querySelector('div').style.setProperty('display', 'none')");62 Assert.True(await waitForXPath.WithTimeout());63 Assert.True(divHidden);64 }65 [PuppeteerTest("waittask.spec.ts", "Frame.waitForXPath", "should return the element handle")]66 [PuppeteerFact]67 public async Task ShouldReturnTheElementHandle()68 {69 var waitForXPath = Page.WaitForXPathAsync("//*[@class=\"zombo\"]");70 await Page.SetContentAsync("<div class='zombo'>anything</div>");71 Assert.Equal("anything", await Page.EvaluateFunctionAsync<string>("x => x.textContent", await waitForXPath));72 }73 [PuppeteerTest("waittask.spec.ts", "Frame.waitForXPath", "should allow you to select a text node")]74 [PuppeteerFact]75 public async Task ShouldAllowYouToSelectATextNode()76 {77 await Page.SetContentAsync("<div>some text</div>");78 var text = await Page.WaitForXPathAsync("//div/text()");79 Assert.Equal(3 /* Node.TEXT_NODE */, await (await text.GetPropertyAsync("nodeType")).JsonValueAsync<int>());80 }81 [PuppeteerTest("waittask.spec.ts", "Frame.waitForXPath", "should allow you to select an element with single slash")]82 [PuppeteerFact]83 public async Task ShouldAllowYouToSelectAnElementWithSingleSlash()84 {85 await Page.SetContentAsync("<div>some text</div>");86 var waitForXPath = Page.WaitForXPathAsync("/html/body/div");87 Assert.Equal("some text", await Page.EvaluateFunctionAsync<string>("x => x.textContent", await waitForXPath));88 }89 [PuppeteerTest("waittask.spec.ts", "Frame.waitForXPath", "should respect timeout")]90 [PuppeteerFact]91 public async Task ShouldRespectTimeout()92 {93 var exception = await Assert.ThrowsAsync<WaitTaskTimeoutException>(()94 => Page.WaitForXPathAsync("//div", new WaitForSelectorOptions { Timeout = 10 }));95 Assert.Contains("waiting for XPath '//div' failed: timeout", exception.Message);96 }97 }98}...

Full Screen

Full Screen

WontImplementTests.cs

Source:WontImplementTests.cs Github

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp.Tests.Attributes;4using PuppeteerSharp.Xunit;5using Xunit;6using Xunit.Abstractions;7namespace PuppeteerSharp.Tests8{9 [Collection(TestConstants.TestFixtureCollectionName)]10 public class WontImplementTests : PuppeteerPageBaseTest11 {12 public WontImplementTests(ITestOutputHelper output) : base(output)13 {14 }15 // We don't implement pipes16 [PuppeteerTest("chromiumonly.spec.ts", "Puppeteer.launch |pipe| option", "should support the pipe option")]17 [PuppeteerTest("chromiumonly.spec.ts", "Puppeteer.launch |pipe| option", "should support the pipe argument")]18 [PuppeteerTest("chromiumonly.spec.ts", "Puppeteer.launch |pipe| option", "should fire \"disconnected\" when closing with pipe")]19 [PuppeteerTest("navigation.spec.ts", "should not leak listeners during navigation")]20 [PuppeteerTest("navigation.spec.ts", "should not leak listeners during bad navigation")]21 [PuppeteerTest("navigation.spec.ts", "should not leak listeners during navigation of 11 pages")]22 [PuppeteerTest("navigation.spec.ts", "should throw if networkidle is passed as an option")]23 [PuppeteerTest("launcher.spec.ts", "Puppeteer.launch", "should report the correct product")] //We don't use the product in this way24 [PuppeteerTest("launcher.spec.ts", "Puppeteer.launch", "falls back to launching chrome if there is an unknown product but logs a warning")]25 [PuppeteerTest("tracing.spec.ts", "Tracing", "should return null in case of Buffer error")]26 [PuppeteerTest("tracing.spec.ts", "Tracing", "should properly fail if readProtocolStream errors out")]27 [PuppeteerTest("fixtures.spec.ts", "Fixtures", "dumpio option should work with pipe option")]28 [PuppeteerTest("EventEmitter.spec.ts", "once", "only calls the listener once and then removes it")]29 [PuppeteerTest("EventEmitter.spec.ts", "once", "supports chaining")]30 [PuppeteerTest("EventEmitter.spec.ts", "emit", "calls all the listeners for an event")]31 [PuppeteerTest("EventEmitter.spec.ts", "emit", "passes data through to the listener")]32 [PuppeteerTest("EventEmitter.spec.ts", "emit", "returns true if the event has listeners")]33 [PuppeteerTest("EventEmitter.spec.ts", "emit", "returns false if the event has listeners")]34 [PuppeteerTest("EventEmitter.spec.ts", "listenerCount", "returns the number of listeners for the given event")]35 [PuppeteerTest("EventEmitter.spec.ts", "removeAllListeners", "removes every listener from all events by default")]36 [PuppeteerTest("EventEmitter.spec.ts", "removeAllListeners", "returns the emitter for chaining")]37 [PuppeteerTest("EventEmitter.spec.ts", "removeAllListeners", "can filter to remove only listeners for a given event name")]38 [PuppeteerTest("emulation.spec.ts", "Page.emulateMediaType", "should throw in case of bad argument")]39 [PuppeteerTest("emulation.spec.ts", "Page.emulateMediaFeatures", "should throw in case of bad argument")]40 [PuppeteerTest("emulation.spec.ts", "Page.emulateVisionDeficiency", "should throw for invalid vision deficiencies")]41 [PuppeteerTest("waittask.spec.ts", "Page.waitFor", "should throw when unknown type")]42 [PuppeteerTest("waittask.spec.ts", "Page.waitFor", "should log a deprecation warning")]43 [PuppeteerTest("waittask.spec.ts", "Frame.waitForFunction", "should accept a string")]44 [PuppeteerTest("waittask.spec.ts", "Frame.waitForFunction", "should throw on bad polling value")]45 [PuppeteerTest("network.spec.ts", "Page.setExtraHTTPHeaders", "should throw for non-string header values")]46 [PuppeteerFact]47 public void TheseTesstWontBeImplemented()48 {49 }50 }51}...

Full Screen

Full Screen

PageWaitForTests.cs

Source:PageWaitForTests.cs Github

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp.Tests.Attributes;4using PuppeteerSharp.Xunit;5using Xunit;6using Xunit.Abstractions;7namespace PuppeteerSharp.Tests.WaitForTests8{9 [Collection(TestConstants.TestFixtureCollectionName)]10 public class PageWaitForTests : PuppeteerPageBaseTest11 {12 public PageWaitForTests(ITestOutputHelper output) : base(output)13 {14 }15 [PuppeteerTest("waittask.spec.ts", "Page.waitFor", "should wait for selector")]16 [PuppeteerFact]17 public async Task ShouldWaitForSelector()18 {19 var found = false;20 var waitFor = Page.WaitForSelectorAsync("div").ContinueWith(_ => found = true);21 await Page.GoToAsync(TestConstants.EmptyPage);22 Assert.False(found);23 await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");24 await waitFor;25 Assert.True(found);26 }27 [PuppeteerTest("waittask.spec.ts", "Page.waitFor", "should wait for an xpath")]28 [PuppeteerFact]29 public async Task ShouldWaitForAnXpath()30 {31 var found = false;32 var waitFor = Page.WaitForXPathAsync("//div").ContinueWith(_ => found = true);33 await Page.GoToAsync(TestConstants.EmptyPage);34 Assert.False(found);35 await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");36 await waitFor;37 Assert.True(found);38 }39 [PuppeteerTest("waittask.spec.ts", "Page.waitFor", "should not allow you to select an element with single slash xpath")]40 [PuppeteerFact]41 public async Task ShouldNotAllowYouToSelectAnElementWithSingleSlashXpath()42 {43 await Page.SetContentAsync("<div>some text</div>");44 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(() =>45 Page.WaitForSelectorAsync("/html/body/div"));46 Assert.NotNull(exception);47 }48 [PuppeteerTest("waittask.spec.ts", "Page.waitFor", "should timeout")]49 [PuppeteerFact]50 public async Task ShouldTimeout()51 {52 var startTime = DateTime.Now;53 var timeout = 42;54 await Page.WaitForTimeoutAsync(timeout);55 Assert.True((DateTime.Now - startTime).TotalMilliseconds > timeout / 2);56 }57 [PuppeteerTest("waittask.spec.ts", "Page.waitFor", "should work with multiline body")]58 [PuppeteerFact]59 public async Task ShouldWorkWithMultilineBody()60 {61 var result = await Page.WaitForExpressionAsync(@"62 (() => true)()63 ");64 Assert.True(await result.JsonValueAsync<bool>());65 }66 [PuppeteerTest("waittask.spec.ts", "Page.waitFor", "should wait for predicate")]67 [PuppeteerFact]68 public Task ShouldWaitForPredicate()69 => Task.WhenAll(70 Page.WaitForFunctionAsync("() => window.innerWidth < 100"),71 Page.SetViewportAsync(new ViewPortOptions { Width = 10, Height = 10 }));72 [PuppeteerTest("waittask.spec.ts", "Page.waitFor", "should wait for predicate with arguments")]73 [PuppeteerFact]74 public async Task ShouldWaitForPredicateWithArguments()75 => await Page.WaitForFunctionAsync("(arg1, arg2) => arg1 !== arg2", new WaitForFunctionOptions(), 1, 2);76 }77}...

Full Screen

Full Screen

FileChooser.cs

Source:FileChooser.cs Github

copy

Full Screen

1using System;2using System.IO;3using System.Linq;4using System.Threading.Tasks;5using PuppeteerSharp.Messaging;6namespace PuppeteerSharp7{8 /// <summary>9 /// <see cref="FileChooser"/> objects are returned via the <seealso cref="Page.WaitForFileChooserAsync(WaitForFileChooserOptions)"/> method.10 /// File choosers let you react to the page requesting for a file.11 /// </summary>12 /// <example>13 /// <code>14 /// <![CDATA[15 /// var waitTask = page.WaitForFileChooserAsync();16 /// await Task.WhenAll(17 /// waitTask,18 /// page.ClickAsync("#upload-file-button")); // some button that triggers file selection19 /// 20 /// await waitTask.Result.AcceptAsync('/tmp/myfile.pdf');21 /// ]]>22 /// </code>23 /// </example>24 /// <remarks>25 /// In browsers, only one file chooser can be opened at a time.26 /// All file choosers must be accepted or canceled. Not doing so will prevent subsequent file choosers from appearing.27 /// </remarks>28 public class FileChooser29 {30 private CDPSession _client;31 private bool _handled;32 internal FileChooser(CDPSession client, PageFileChooserOpenedResponse e)33 {34 _client = client;35 IsMultiple = e.Mode != "selectSingle";36 _handled = false;37 }38 /// <summary>39 /// Whether file chooser allow for <see href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#attr-multiple">multiple</see> file selection.40 /// </summary>41 public bool IsMultiple { get; }42 /// <summary>43 /// Accept the file chooser request with given paths. 44 /// If some of the filePaths are relative paths, then they are resolved relative to the current working directory.45 /// </summary>46 /// <param name="filePaths">File paths to send to the file chooser</param>47 /// <returns>A task that resolves after the accept message is processed by the browser</returns>48 public Task AcceptAsync(params string[] filePaths)49 {50 if (_handled)51 {52 throw new PuppeteerException("Cannot accept FileChooser which is already handled!");53 }54 _handled = true;55 var files = filePaths.Select(Path.GetFullPath);56 return _client.SendAsync("Page.handleFileChooser", new PageHandleFileChooserRequest57 {58 Action = FileChooserAction.Accept,59 Files = files,60 });61 }62 /// <summary>63 /// Closes the file chooser without selecting any files.64 /// </summary>65 /// <returns>A task that resolves after the cancel message is processed by the browser</returns>66 public Task CancelAsync()67 {68 if (_handled)69 {70 throw new PuppeteerException("Cannot accept FileChooser which is already handled!");71 }72 _handled = true;73 return _client.SendAsync("Page.handleFileChooser", new PageHandleFileChooserRequest74 {75 Action = FileChooserAction.Cancel76 });77 }78 }79}...

Full Screen

Full Screen

WaitTaskTimeoutException.cs

Source:WaitTaskTimeoutException.cs Github

copy

Full Screen

...5 /// <summary>6 /// Timeout exception that might be thrown by <c>WaitFor</c> methods in <see cref="Frame"/>.7 /// </summary>8 [Serializable]9 public class WaitTaskTimeoutException : PuppeteerException10 {11 /// <summary>12 /// Timeout that caused the exception13 /// </summary>14 /// <value>The timeout.</value>15 public int Timeout { get; }16 /// <summary>17 /// Element type the WaitTask was waiting for18 /// </summary>19 /// <value>The element.</value>20 public string ElementType { get; }21 /// <summary>22 /// Initializes a new instance of the <see cref="PuppeteerSharp.WaitTaskTimeoutException"/> class.23 /// </summary>24 public WaitTaskTimeoutException()25 {26 }27 /// <summary>28 /// Initializes a new instance of the <see cref="PuppeteerSharp.WaitTaskTimeoutException"/> class.29 /// </summary>30 /// <param name="message">Message.</param>31 public WaitTaskTimeoutException(string message) : base(message)32 {33 }34 /// <summary>35 /// Initializes a new instance of the <see cref="PuppeteerSharp.WaitTaskTimeoutException"/> class.36 /// </summary>37 /// <param name="timeout">Timeout.</param>38 /// <param name="elementType">Element type.</param>39 public WaitTaskTimeoutException(int timeout, string elementType) :40 base($"waiting for {elementType} failed: timeout {timeout}ms exceeded")41 {42 Timeout = timeout;43 ElementType = elementType;44 }45 /// <summary>46 /// Initializes a new instance of the <see cref="PuppeteerSharp.WaitTaskTimeoutException"/> class.47 /// </summary>48 /// <param name="message">Message.</param>49 /// <param name="innerException">Inner exception.</param>50 public WaitTaskTimeoutException(string message, Exception innerException) : base(message, innerException)51 {52 }53 /// <summary>54 /// Initializes a new instance of the <see cref="PuppeteerSharp.WaitTaskTimeoutException"/> class.55 /// </summary>56 /// <param name="info">Info.</param>57 /// <param name="context">Context.</param>58 protected WaitTaskTimeoutException(SerializationInfo info, StreamingContext context) : base(info, context)59 {60 }61 }62}...

Full Screen

Full Screen

WaitTask

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 static async Task Main(string[] args)6 {7 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 Args = new string[] { "--no-sandbox" }11 });12 var page = await browser.NewPageAsync();13 var waitTask = new WaitTask(page);14 await page.TypeAsync("input[title='Search']", "Puppeteer");15 await page.ClickAsync("input[value='Google Search']");16 await waitTask.WaitForSelectorAsync("h3");17 var results = await page.EvaluateExpressionAsync<string[]>("Array.from(document.querySelectorAll('h3')).map(x => x.textContent)");18 foreach (var result in results)19 {20 Console.WriteLine(result);21 }22 await browser.CloseAsync();23 }24}

Full Screen

Full Screen

WaitTask

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 waitTask = new WaitTask();9 var task = waitTask.WaitAsync(5000);10 Console.WriteLine("Waiting for 5 seconds");11 await task;12 Console.WriteLine("5 s

Full Screen

Full Screen

WaitTask

Using AI Code Generation

copy

Full Screen

1var task = new WaitTask();2await task.WaitAsync(1000);3var task = new WaitTask();4await task.WaitAsync(1000);5var task = new WaitTask();6await task.WaitAsync(1000);7var task = new WaitTask();8await task.WaitAsync(1000);9var task = new WaitTask();10await task.WaitAsync(1000);11var task = new WaitTask();12await task.WaitAsync(1000);13var task = new WaitTask();14await task.WaitAsync(1000);15var task = new WaitTask();16await task.WaitAsync(1000);17var task = new WaitTask();18await task.WaitAsync(1000);19var task = new WaitTask();20await task.WaitAsync(1000);21var task = new WaitTask();22await task.WaitAsync(1000);23var task = new WaitTask();24await task.WaitAsync(1000);25var task = new WaitTask();26await task.WaitAsync(1000);27var task = new WaitTask();28await task.WaitAsync(1000);29var task = new WaitTask();

Full Screen

Full Screen

WaitTask

Using AI Code Generation

copy

Full Screen

1{2 {3 static void Main(string[] args)4 {5 WaitTask wt = new WaitTask();6 wt.Wait();7 }8 }9}10{11 {12 static void Main(string[] args)13 {14 WaitTask wt = new WaitTask();15 wt.Wait();16 }17 }18}19{20 {21 static void Main(string[] args)22 {23 WaitTask wt = new WaitTask();24 wt.Wait();25 }26 }27}28{29 {30 static void Main(string[] args)31 {32 WaitTask wt = new WaitTask();33 wt.Wait();34 }35 }36}37{38 {39 static void Main(string[] args)40 {41 WaitTask wt = new WaitTask();42 wt.Wait();43 }44 }45}46{47 {48 static void Main(string[] args)49 {50 WaitTask wt = new WaitTask();51 wt.Wait();52 }53 }54}55{56 {57 static void Main(string[] args)58 {59 WaitTask wt = new WaitTask();60 wt.Wait();61 }62 }63}64{65 {66 static void Main(string[] args)67 {68 WaitTask wt = new WaitTask();69 wt.Wait();70 }71 }72}73{

Full Screen

Full Screen

WaitTask

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3{4 {5 public static Task WaitForNavigationAsync(this Page page, NavigationOptions options = null)6 {7 return page.WaitForNavigationAsync(options, null);8 }9 public static Task WaitForNavigationAsync(this Page page, NavigationOptions options, Action<WaitTask> callback)10 {11 return page.WaitForNavigationAsync(options, callback, null);12 }13 public static Task WaitForNavigationAsync(this Page page, NavigationOptions options, Action<WaitTask> callback, Func<WaitTask, Task> task)14 {15 return page.WaitForNavigationAsync(options, callback, task, null);16 }17 public static Task WaitForNavigationAsync(this Page page, NavigationOptions options, Action<WaitTask> callback, Func<WaitTask, Task> task, Func<WaitTask, Task> task2)18 {19 return page.WaitForNavigationAsync(options, callback, task, task2, null);20 }21 public static Task WaitForNavigationAsync(this Page page, NavigationOptions options, Action<WaitTask> callback, Func<WaitTask, Task> task, Func<WaitTask, Task> task2, Func<WaitTask, Task> task3)22 {23 return page.WaitForNavigationAsync(options, callback, task, task3, task3, null);24 }25 public static Task WaitForNavigationAsync(this Page page, NavigationOptions options, Action<WaitTask> callback, Func<WaitTask, Task> task, Func<WaitTask, Task> task2, Func<WaitTask, Task> task3, Func<WaitTask, Task> task4)26 {27 return page.WaitForNavigationAsync(options, callback, task, task3, task3, task4);28 }29 public static Task WaitForNavigationAsync(this Page page, NavigationOptions options, Action<WaitTask> callback, Func<WaitTask, Task> task, Func<WaitTask, Task> task2, Func<WaitTask, Task> task3, Func<WaitTask, Task> task4, Func<WaitTask, Task> task5)30 {31 return page.WaitForNavigationAsync(options, callback, task, task3, task3, task4, task5);32 }33 public static Task WaitForNavigationAsync(this Page page, NavigationOptions options, Action<WaitTask> callback, Func<WaitTask, Task

Full Screen

Full Screen

WaitTask

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4using System.IO;5{6 {7 public static async Task MainAsync()8 {9 var options = new LaunchOptions { Headless = true };10 using (var browser = await Puppeteer.LaunchAsync(options))11 using (var page = await browser.NewPageAsync())12 {13 await page.ScreenshotAsync("screenshot.png");14 await page.ScreenshotAsync("screenshot.pdf");15 }16 }17 }18}19using System;20using System.Threading.Tasks;21using PuppeteerSharp;22using System.IO;23{24 {25 public static async Task MainAsync()26 {27 var options = new LaunchOptions { Headless = true };28 using (var browser = await Puppeteer.LaunchAsync(options))29 using (var page = await browser.NewPageAsync())30 {31 await page.ScreenshotAsync("screenshot.png");32 await page.ScreenshotAsync("screenshot.pdf");33 }34 }35 }36}37using System;38using System.Threading.Tasks;39using PuppeteerSharp;40using System.IO;41{42 {43 public static async Task MainAsync()44 {45 var options = new LaunchOptions { Headless = true };46 using (var browser = await Puppeteer.LaunchAsync(options))47 using (var page = await browser.NewPageAsync())48 {49 await page.ScreenshotAsync("screenshot.png");50 await page.ScreenshotAsync("screenshot.pdf");51 }52 }53 }54}

Full Screen

Full Screen

WaitTask

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 WaitTask wait = new WaitTask();9 wait.wait(5000);10 Console.WriteLine("Waited 5 seconds");11 }12 }13}14using System;15using System.Threading.Tasks;16using PuppeteerSharp;17{18 {19 static void Main(string[] args)20 {21 WaitTask wait = new WaitTask();22 wait.wait(10000);23 Console.WriteLine("Waited 10 seconds");24 }25 }26}27using System;28using System.Threading.Tasks;29using PuppeteerSharp;30{31 {32 static void Main(string[] args)33 {34 WaitTask wait = new WaitTask();35 wait.wait(15000);36 Console.WriteLine("Waited 15 seconds");37 }38 }39}40using System;41using System.Threading.Tasks;42using PuppeteerSharp;43{44 {45 static void Main(string[] args)46 {47 WaitTask wait = new WaitTask();

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.

Most used methods in WaitTask

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful