Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.Frame.WaitForNavigationAsync
Page.cs
Source:Page.cs
...259 public Task<IWebSocket> WaitForWebSocketAsync(PageWaitForWebSocketOptions options = default)260 => InnerWaitForEventAsync(PageEvent.WebSocket, null, options?.Predicate, options?.Timeout);261 public Task<IWorker> WaitForWorkerAsync(PageWaitForWorkerOptions options = default)262 => InnerWaitForEventAsync(PageEvent.Worker, null, options?.Predicate, options?.Timeout);263 public Task<IResponse> WaitForNavigationAsync(PageWaitForNavigationOptions options = default)264 => MainFrame.WaitForNavigationAsync(new()265 {266 UrlString = options?.UrlString,267 UrlRegex = options?.UrlRegex,268 UrlFunc = options?.UrlFunc,269 WaitUntil = options?.WaitUntil,270 Timeout = options?.Timeout,271 });272 public Task<IResponse> RunAndWaitForNavigationAsync(Func<Task> action, PageRunAndWaitForNavigationOptions options = default)273 => MainFrame.RunAndWaitForNavigationAsync(action, new()274 {275 UrlString = options?.UrlString,276 UrlRegex = options?.UrlRegex,277 UrlFunc = options?.UrlFunc,278 WaitUntil = options?.WaitUntil,279 Timeout = options?.Timeout,280 });281 public Task<IRequest> WaitForRequestAsync(string urlOrPredicate, PageWaitForRequestOptions options = default)282 => InnerWaitForEventAsync(PageEvent.Request, null, e => Context.UrlMatches(e.Url, urlOrPredicate), options?.Timeout);283 public Task<IRequest> WaitForRequestAsync(Regex urlOrPredicate, PageWaitForRequestOptions options = default)284 => InnerWaitForEventAsync(PageEvent.Request, null, e => urlOrPredicate.IsMatch(e.Url), options?.Timeout);285 public Task<IRequest> WaitForRequestAsync(Func<IRequest, bool> urlOrPredicate, PageWaitForRequestOptions options = default)286 => InnerWaitForEventAsync(PageEvent.Request, null, e => urlOrPredicate(e), options?.Timeout);287 public Task<IRequest> WaitForRequestFinishedAsync(PageWaitForRequestFinishedOptions options = default)...
PageRouteTests.cs
Source:PageRouteTests.cs
...106 <input type=""hidden"" id=""foo"" name=""foo"" value=""FOOBAR"">107 </form>");108 await TaskUtils.WhenAll(109 Page.EvalOnSelectorAsync("form", "form => form.submit()"),110 Page.WaitForNavigationAsync()111 );112 }113 [PlaywrightTest("page-route.spec.ts", "should work when header manipulation headers with redirect")]114 public async Task ShouldWorkWhenHeaderManipulationHeadersWithRedirect()115 {116 Server.SetRedirect("/rrredirect", "/empty.html");117 await Page.RouteAsync("**/*", (route) =>118 {119#pragma warning disable 0612120 var headers = new Dictionary<string, string>(route.Request.Headers.ToDictionary(x => x.Key, x => x.Value)) { ["foo"] = "bar" };121#pragma warning restore 0612122 route.ContinueAsync(new() { Headers = headers });123 });124 await Page.GotoAsync(Server.Prefix + "/rrredirect");...
Frame.cs
Source:Frame.cs
...160 {161 waiter?.Dispose();162 }163 }164 public async Task<IResponse> WaitForNavigationAsync(FrameWaitForNavigationOptions options = default)165 {166 WaitUntilState waitUntil2 = options?.WaitUntil ?? WaitUntilState.Load;167 using var waiter = SetupNavigationWaiter("frame.WaitForNavigationAsync", options?.Timeout);168 string toUrl = !string.IsNullOrEmpty(options?.UrlString) ? $" to \"{options?.UrlString}\"" : string.Empty;169 waiter.Log($"waiting for navigation{toUrl} until \"{waitUntil2}\"");170 var navigatedEventTask = waiter.WaitForEventAsync<FrameNavigatedEventArgs>(171 this,172 "Navigated",173 e =>174 {175 // Any failed navigation results in a rejection.176 if (e.Error != null)177 {178 return true;179 }180 waiter.Log($" navigated to \"{e.Url}\"");181 return UrlMatches(e.Url, options?.UrlString, options?.UrlRegex, options?.UrlFunc);182 });183 var navigatedEvent = await navigatedEventTask.ConfigureAwait(false);184 if (navigatedEvent.Error != null)185 {186 var ex = new PlaywrightException(navigatedEvent.Error);187 await waiter.WaitForPromiseAsync(Task.FromException<object>(ex)).ConfigureAwait(false);188 }189 if (!_loadStates.Select(s => s.ToValueString()).Contains(waitUntil2.ToValueString()))190 {191 await waiter.WaitForEventAsync<WaitUntilState>(192 this,193 "LoadState",194 e =>195 {196 waiter.Log($" \"{e}\" event fired");197 return e.ToValueString() == waitUntil2.ToValueString();198 }).ConfigureAwait(false);199 }200 var request = navigatedEvent.NewDocument?.Request?.Object;201 var response = request != null202 ? await waiter.WaitForPromiseAsync(request.FinalRequest.ResponseAsync()).ConfigureAwait(false)203 : null;204 return response;205 }206 public async Task<IResponse> RunAndWaitForNavigationAsync(Func<Task> action, FrameRunAndWaitForNavigationOptions options = default)207 {208 var result = WaitForNavigationAsync(new()209 {210 UrlString = options?.UrlString,211 UrlRegex = options?.UrlRegex,212 UrlFunc = options?.UrlFunc,213 WaitUntil = options?.WaitUntil,214 Timeout = options?.Timeout,215 });216 if (action != null)217 {218 await WrapApiBoundaryAsync(() => Task.WhenAll(result, action())).ConfigureAwait(false);219 }220 return await result.ConfigureAwait(false);221 }222 public Task TapAsync(string selector, FrameTapOptions options = default)223 => _channel.TapAsync(224 selector,225 modifiers: options?.Modifiers,226 position: options?.Position,227 timeout: options?.Timeout,228 force: options?.Force,229 noWaitAfter: options?.NoWaitAfter,230 trial: options?.Trial,231 strict: options?.Strict);232 internal Task<int> QueryCountAsync(string selector)233 => _channel.QueryCountAsync(selector);234 public Task<string> ContentAsync() => _channel.ContentAsync();235 public Task FocusAsync(string selector, FrameFocusOptions options = default)236 => _channel.FocusAsync(selector, options?.Timeout, options?.Strict);237 public Task TypeAsync(string selector, string text, FrameTypeOptions options = default)238 => _channel.TypeAsync(239 selector,240 text,241 delay: options?.Delay,242 timeout: options?.Timeout,243 noWaitAfter: options?.NoWaitAfter,244 strict: options?.Strict);245 public Task<string> GetAttributeAsync(string selector, string name, FrameGetAttributeOptions options = default)246 => _channel.GetAttributeAsync(selector, name, options?.Timeout, options?.Strict);247 public Task<string> InnerHTMLAsync(string selector, FrameInnerHTMLOptions options = default)248 => _channel.InnerHTMLAsync(selector, options?.Timeout, options?.Strict);249 public Task<string> InnerTextAsync(string selector, FrameInnerTextOptions options = default)250 => _channel.InnerTextAsync(selector, options?.Timeout, options?.Strict);251 public Task<string> TextContentAsync(string selector, FrameTextContentOptions options = default)252 => _channel.TextContentAsync(selector, options?.Timeout, options?.Strict);253 public Task HoverAsync(string selector, FrameHoverOptions options = default)254 => _channel.HoverAsync(255 selector,256 position: options?.Position,257 modifiers: options?.Modifiers,258 force: options?.Force,259 timeout: options?.Timeout,260 trial: options?.Trial,261 strict: options?.Strict);262 public Task PressAsync(string selector, string key, FramePressOptions options = default)263 => _channel.PressAsync(264 selector,265 key,266 delay: options?.Delay,267 timeout: options?.Timeout,268 noWaitAfter: options?.NoWaitAfter,269 strict: options?.Strict);270 public Task DispatchEventAsync(string selector, string type, object eventInit = default, FrameDispatchEventOptions options = default)271 => _channel.DispatchEventAsync(272 selector,273 type,274 ScriptsHelper.SerializedArgument(eventInit),275 options?.Timeout,276 options?.Strict);277 public Task FillAsync(string selector, string value, FrameFillOptions options = default)278 => _channel.FillAsync(selector, value, force: options?.Force, timeout: options?.Timeout, noWaitAfter: options?.NoWaitAfter, options?.Strict);279 public async Task<IElementHandle> AddScriptTagAsync(FrameAddScriptTagOptions options = default)280 {281 var content = options?.Content;282 if (!string.IsNullOrEmpty(options?.Path))283 {284 content = File.ReadAllText(options.Path);285 content += "//# sourceURL=" + options.Path.Replace("\n", string.Empty);286 }287 return (await _channel.AddScriptTagAsync(options?.Url, options?.Path, content, options?.Type).ConfigureAwait(false)).Object;288 }289 public async Task<IElementHandle> AddStyleTagAsync(FrameAddStyleTagOptions options = default)290 {291 var content = options?.Content;292 if (!string.IsNullOrEmpty(options?.Path))293 {294 content = File.ReadAllText(options.Path);295 content += "//# sourceURL=" + options.Path.Replace("\n", string.Empty);296 }297 return (await _channel.AddStyleTagAsync(options?.Url, options?.Path, content).ConfigureAwait(false)).Object;298 }299 public Task SetInputFilesAsync(string selector, string files, FrameSetInputFilesOptions options = default)300 => SetInputFilesAsync(selector, new[] { files }, options);301 public async Task SetInputFilesAsync(string selector, IEnumerable<string> files, FrameSetInputFilesOptions options = default)302 {303 var converted = await SetInputFilesHelpers.ConvertInputFilesAsync(files, (BrowserContext)Page.Context).ConfigureAwait(false);304 if (converted.Files != null)305 {306 await _channel.SetInputFilesAsync(selector, converted.Files, options?.NoWaitAfter, options?.Timeout, options?.Strict).ConfigureAwait(false);307 }308 else309 {310 await _channel.SetInputFilePathsAsync(selector, converted?.LocalPaths, converted?.Streams, options?.NoWaitAfter, options?.Timeout, options?.Strict).ConfigureAwait(false);311 }312 }313 public Task SetInputFilesAsync(string selector, FilePayload files, FrameSetInputFilesOptions options = default)314 => SetInputFilesAsync(selector, new[] { files }, options);315 public async Task SetInputFilesAsync(string selector, IEnumerable<FilePayload> files, FrameSetInputFilesOptions options = default)316 {317 var converted = SetInputFilesHelpers.ConvertInputFiles(files);318 await _channel.SetInputFilesAsync(selector, converted.Files, noWaitAfter: options?.NoWaitAfter, timeout: options?.Timeout, options?.Strict).ConfigureAwait(false);319 }320 public Task ClickAsync(string selector, FrameClickOptions options = default)321 => _channel.ClickAsync(322 selector,323 delay: options?.Delay,324 button: options?.Button,325 clickCount: options?.ClickCount,326 modifiers: options?.Modifiers,327 position: options?.Position,328 timeout: options?.Timeout,329 force: options?.Force,330 noWaitAfter: options?.NoWaitAfter,331 trial: options?.Trial,332 strict: options?.Strict);333 public Task DblClickAsync(string selector, FrameDblClickOptions options = default)334 => _channel.DblClickAsync(335 selector,336 delay: options?.Delay,337 button: options?.Button,338 position: options?.Position,339 modifiers: options?.Modifiers,340 timeout: options?.Timeout,341 force: options?.Force,342 noWaitAfter: options?.NoWaitAfter,343 trial: options?.Trial,344 strict: options?.Strict);345 public Task CheckAsync(string selector, FrameCheckOptions options = default)346 => _channel.CheckAsync(347 selector,348 position: options?.Position,349 timeout: options?.Timeout,350 force: options?.Force,351 noWaitAfter: options?.NoWaitAfter,352 trial: options?.Trial,353 strict: options?.Strict);354 public Task UncheckAsync(string selector, FrameUncheckOptions options = default)355 => _channel.UncheckAsync(356 selector,357 position: options?.Position,358 timeout: options?.Timeout,359 force: options?.Force,360 noWaitAfter: options?.NoWaitAfter,361 trial: options?.Trial,362 strict: options?.Strict);363 public Task SetCheckedAsync(string selector, bool checkedState, FrameSetCheckedOptions options = null)364 => checkedState ?365 _channel.CheckAsync(366 selector,367 position: options?.Position,368 timeout: options?.Timeout,369 force: options?.Force,370 noWaitAfter: options?.NoWaitAfter,371 trial: options?.Trial,372 strict: options?.Strict)373 : _channel.UncheckAsync(374 selector,375 position: options?.Position,376 timeout: options?.Timeout,377 force: options?.Force,378 noWaitAfter: options?.NoWaitAfter,379 trial: options?.Trial,380 strict: options?.Strict);381 public Task SetContentAsync(string html, FrameSetContentOptions options = default)382 => _channel.SetContentAsync(html, timeout: options?.Timeout, waitUntil: options?.WaitUntil);383 public Task<string> InputValueAsync(string selector, FrameInputValueOptions options = null)384 => _channel.InputValueAsync(selector, options?.Timeout, options?.Strict);385 public async Task<IElementHandle> QuerySelectorAsync(string selector)386 => (await _channel.QuerySelectorAsync(selector).ConfigureAwait(false))?.Object;387 public async Task<IReadOnlyList<IElementHandle>> QuerySelectorAllAsync(string selector)388 => (await _channel.QuerySelectorAllAsync(selector).ConfigureAwait(false)).Select(c => ((ElementHandleChannel)c).Object).ToList().AsReadOnly();389 public async Task<IJSHandle> WaitForFunctionAsync(string expression, object arg = default, FrameWaitForFunctionOptions options = default)390 => (await _channel.WaitForFunctionAsync(391 expression: expression,392 arg: ScriptsHelper.SerializedArgument(arg),393 timeout: options?.Timeout,394 polling: options?.PollingInterval).ConfigureAwait(false)).Object;395 public async Task<IElementHandle> WaitForSelectorAsync(string selector, FrameWaitForSelectorOptions options = default)396 => (await _channel.WaitForSelectorAsync(397 selector: selector,398 state: options?.State,399 timeout: options?.Timeout,400 strict: options?.Strict,401 omitReturnValue: false).ConfigureAwait(false))?.Object;402 public async Task<IElementHandle> LocatorWaitForAsync(string selector, LocatorWaitForOptions options = default)403 => (await _channel.WaitForSelectorAsync(404 selector: selector,405 state: options?.State,406 timeout: options?.Timeout,407 strict: true,408 omitReturnValue: true).ConfigureAwait(false))?.Object;409 public async Task<IJSHandle> EvaluateHandleAsync(string script, object args = null)410 => (await _channel.EvaluateExpressionHandleAsync(411 script,412 arg: ScriptsHelper.SerializedArgument(args)).ConfigureAwait(false))?.Object;413 public async Task<JsonElement?> EvaluateAsync(string script, object arg = null)414 => ScriptsHelper.ParseEvaluateResult<JsonElement?>(await _channel.EvaluateExpressionAsync(415 script,416 arg: ScriptsHelper.SerializedArgument(arg)).ConfigureAwait(false));417 public async Task<T> EvaluateAsync<T>(string script, object arg = null)418 => ScriptsHelper.ParseEvaluateResult<T>(await _channel.EvaluateExpressionAsync(419 script,420 arg: ScriptsHelper.SerializedArgument(arg)).ConfigureAwait(false));421 public async Task<JsonElement?> EvalOnSelectorAsync(string selector, string script, object arg = null)422 => ScriptsHelper.ParseEvaluateResult<JsonElement?>(await _channel.EvalOnSelectorAsync(423 selector: selector,424 script,425 arg: ScriptsHelper.SerializedArgument(arg),426 strict: null).ConfigureAwait(false));427 public async Task<T> EvalOnSelectorAsync<T>(string selector, string script, object arg = null)428 => ScriptsHelper.ParseEvaluateResult<T>(await _channel.EvalOnSelectorAsync(429 selector: selector,430 script,431 arg: ScriptsHelper.SerializedArgument(arg),432 strict: null).ConfigureAwait(false));433 public async Task<T> EvalOnSelectorAsync<T>(string selector, string expression, object arg = null, FrameEvalOnSelectorOptions options = null)434 => ScriptsHelper.ParseEvaluateResult<T>(await _channel.EvalOnSelectorAsync(435 selector: selector,436 expression,437 arg: ScriptsHelper.SerializedArgument(arg),438 strict: options?.Strict).ConfigureAwait(false));439 public async Task<JsonElement?> EvalOnSelectorAllAsync(string selector, string script, object arg = null)440 => ScriptsHelper.ParseEvaluateResult<JsonElement?>(await _channel.EvalOnSelectorAllAsync(441 selector: selector,442 script,443 arg: ScriptsHelper.SerializedArgument(arg)).ConfigureAwait(false));444 public async Task<T> EvalOnSelectorAllAsync<T>(string selector, string script, object arg = null)445 => ScriptsHelper.ParseEvaluateResult<T>(await _channel.EvalOnSelectorAllAsync(446 selector: selector,447 script,448 arg: ScriptsHelper.SerializedArgument(arg)).ConfigureAwait(false));449 public ILocator Locator(string selector, FrameLocatorOptions options = null) => new Locator(this, selector, new() { HasTextRegex = options?.HasTextRegex, HasTextString = options?.HasTextString, Has = options?.Has });450 public async Task<IElementHandle> QuerySelectorAsync(string selector, FrameQuerySelectorOptions options = null)451 => (await _channel.QuerySelectorAsync(selector, options?.Strict).ConfigureAwait(false))?.Object;452 public async Task<IResponse> GotoAsync(string url, FrameGotoOptions options = default)453 => (await _channel.GotoAsync(454 url,455 timeout: options?.Timeout,456 waitUntil: options?.WaitUntil,457 referer: options?.Referer).ConfigureAwait(false))?.Object;458 public Task<bool> IsCheckedAsync(string selector, FrameIsCheckedOptions options = default)459 => _channel.IsCheckedAsync(selector, timeout: options?.Timeout, options?.Strict);460 public Task<bool> IsDisabledAsync(string selector, FrameIsDisabledOptions options = default)461 => _channel.IsDisabledAsync(selector, timeout: options?.Timeout, options?.Strict);462 public Task<bool> IsEditableAsync(string selector, FrameIsEditableOptions options = default)463 => _channel.IsEditableAsync(selector, timeout: options?.Timeout, options?.Strict);464 public Task<bool> IsEnabledAsync(string selector, FrameIsEnabledOptions options = default)465 => _channel.IsEnabledAsync(selector, timeout: options?.Timeout, options?.Strict);466#pragma warning disable CS0612 // Type or member is obsolete467 public Task<bool> IsHiddenAsync(string selector, FrameIsHiddenOptions options = default)468 => _channel.IsHiddenAsync(selector, timeout: options?.Timeout, options?.Strict);469 public Task<bool> IsVisibleAsync(string selector, FrameIsVisibleOptions options = default)470 => _channel.IsVisibleAsync(selector, timeout: options?.Timeout, options?.Strict);471#pragma warning restore CS0612 // Type or member is obsolete472 public Task WaitForURLAsync(string url, FrameWaitForURLOptions options = default)473 => WaitForURLAsync(url, null, null, options);474 public Task WaitForURLAsync(Regex url, FrameWaitForURLOptions options = default)475 => WaitForURLAsync(null, url, null, options);476 public Task WaitForURLAsync(Func<string, bool> url, FrameWaitForURLOptions options = default)477 => WaitForURLAsync(null, null, url, options);478 public Task DragAndDropAsync(string source, string target, FrameDragAndDropOptions options = null)479 => _channel.DragAndDropAsync(source, target, options?.Force, options?.NoWaitAfter, options?.Timeout, options?.Trial, options?.Strict);480 internal Task<FrameExpectResult> ExpectAsync(string selector, string expression, FrameExpectOptions options = null) =>481 _channel.ExpectAsync(selector, expression, expressionArg: options?.ExpressionArg, expectedText: options?.ExpectedText, expectedNumber: options?.ExpectedNumber, expectedValue: options?.ExpectedValue, useInnerText: options?.UseInnerText, isNot: options?.IsNot, timeout: options?.Timeout);482 private Task WaitForURLAsync(string urlString, Regex urlRegex, Func<string, bool> urlFunc, FrameWaitForURLOptions options = default)483 {484 if (UrlMatches(Url, urlString, urlRegex, urlFunc))485 {486 return WaitForLoadStateAsync(ToLoadState(options?.WaitUntil), new() { Timeout = options?.Timeout });487 }488 return WaitForNavigationAsync(489 new()490 {491 UrlString = urlString,492 UrlRegex = urlRegex,493 UrlFunc = urlFunc,494 Timeout = options?.Timeout,495 WaitUntil = options?.WaitUntil,496 });497 }498 private LoadState? ToLoadState(WaitUntilState? waitUntilState)499 {500 if (waitUntilState == null)501 {502 return null;...
FrameChannel.cs
Source:FrameChannel.cs
...192 ["content"] = content,193 };194 return Connection.SendMessageToServerAsync<ElementHandleChannel>(Guid, "addStyleTag", args);195 }196 internal Task<ResponseChannel> WaitForNavigationAsync(LoadState? waitUntil, string url, float? timeout)197 {198 var param = new Dictionary<string, object>199 {200 ["timeout"] = timeout,201 ["url"] = url,202 ["waitUntil"] = waitUntil,203 };204 return Connection.SendMessageToServerAsync<ResponseChannel>(Guid, "waitForNavigation", param);205 }206 internal Task WaitForLoadStateAsync(LoadState? state, float? timeout)207 {208 var param = new Dictionary<string, object>209 {210 ["timeout"] = timeout,...
PageAutoWaitingBasicTests.cs
Source:PageAutoWaitingBasicTests.cs
...43 });44 await Page.SetContentAsync($"<a href=\"{Server.EmptyPage}\">empty.html</a>");45 await TaskUtils.WhenAll(46 Page.ClickAsync("a").ContinueWith(_ => messages.Add("click")),47 Page.WaitForNavigationAsync().ContinueWith(_ => messages.Add("navigated")));48 Assert.AreEqual("route|navigated|click", string.Join("|", messages));49 }50 [PlaywrightTest("page-autowaiting-basic.spec.ts", "should await cross-process navigation when clicking anchor")]51 [Ignore("Flacky")]52 public async Task ShouldAwaitCrossProcessNavigationWhenClickingAnchor()53 {54 var messages = new List<string>();55 Server.SetRoute("/empty.html", context =>56 {57 messages.Add("route");58 context.Response.ContentType = "text/html";59 return context.Response.WriteAsync("<link rel='stylesheet' href='./one-style.css'>");60 });61 await Page.SetContentAsync($"<a href=\"{Server.CrossProcessPrefix}/empty.html\">empty.html</a>");62 await TaskUtils.WhenAll(63 Page.ClickAsync("a").ContinueWith(_ => messages.Add("click")),64 Page.WaitForNavigationAsync().ContinueWith(_ => messages.Add("navigated")));65 Assert.AreEqual("route|navigated|click", string.Join("|", messages));66 }67 [PlaywrightTest("page-autowaiting-basic.spec.ts", "should await form-get on click")]68 [Ignore("Flacky")]69 public async Task ShouldAwaitFormGetOnClick()70 {71 var messages = new List<string>();72 Server.SetRoute("/empty.html?foo=bar", context =>73 {74 messages.Add("route");75 context.Response.ContentType = "text/html";76 return context.Response.WriteAsync("<link rel='stylesheet' href='./one-style.css'>");77 });78 await Page.SetContentAsync($@"79 <form action=""{Server.EmptyPage}"" method=""get"">80 <input name=""foo"" value=""bar"">81 <input type=""submit"" value=""Submit"">82 </form>");83 await TaskUtils.WhenAll(84 Page.ClickAsync("input[type=submit]").ContinueWith(_ => messages.Add("click")),85 Page.WaitForNavigationAsync().ContinueWith(_ => messages.Add("navigated")));86 Assert.AreEqual("route|navigated|click", string.Join("|", messages));87 }88 [PlaywrightTest("page-autowaiting-basic.spec.ts", "should await form-post on click")]89 [Ignore("Flacky")]90 public async Task ShouldAwaitFormPostOnClick()91 {92 var messages = new List<string>();93 Server.SetRoute("/empty.html", context =>94 {95 messages.Add("route");96 context.Response.ContentType = "text/html";97 return context.Response.WriteAsync("<link rel='stylesheet' href='./one-style.css'>");98 });99 await Page.SetContentAsync($@"100 <form action=""{ Server.EmptyPage}"" method=""post"">101 <input name=""foo"" value=""bar"">102 <input type=""submit"" value=""Submit"">103 </form>");104 await TaskUtils.WhenAll(105 Page.ClickAsync("input[type=submit]").ContinueWith(_ => messages.Add("click")),106 Page.WaitForNavigationAsync().ContinueWith(_ => messages.Add("navigated")));107 Assert.AreEqual("route|navigated|click", string.Join("|", messages));108 }109 [PlaywrightTest("page-autowaiting-basic.spec.ts", "should await navigation when assigning location")]110 [Ignore("Flacky")]111 public async Task ShouldAwaitNavigationWhenAssigningLocation()112 {113 var messages = new List<string>();114 Server.SetRoute("/empty.html", context =>115 {116 messages.Add("route");117 context.Response.ContentType = "text/html";118 return context.Response.WriteAsync("<link rel='stylesheet' href='./one-style.css'>");119 });120 await TaskUtils.WhenAll(121 Page.EvaluateAsync($"window.location.href = '{Server.EmptyPage}'").ContinueWith(_ => messages.Add("evaluate")),122 Page.WaitForNavigationAsync().ContinueWith(_ => messages.Add("navigated")));123 Assert.AreEqual("route|navigated|evaluate", string.Join("|", messages));124 }125 [PlaywrightTest("page-autowaiting-basic.spec.ts", "should await navigation when assigning location twice")]126 public async Task ShouldAwaitNavigationWhenAssigningLocationTwice()127 {128 var messages = new List<string>();129 Server.SetRoute("/empty.html?cancel", context =>130 {131 return context.Response.WriteAsync("done");132 });133 Server.SetRoute("/empty.html?override", context =>134 {135 messages.Add("routeoverride");136 return context.Response.WriteAsync("done");137 });138 await Page.EvaluateAsync($@"139 window.location.href = '{Server.EmptyPage}?cancel';140 window.location.href = '{Server.EmptyPage}?override';");141 messages.Add("evaluate");142 Assert.AreEqual("routeoverride|evaluate", string.Join("|", messages));143 }144 [PlaywrightTest("page-autowaiting-basic.spec.ts", "should await navigation when evaluating reload")]145 [Ignore("Flacky")]146 public async Task ShouldAwaitNavigationWhenEvaluatingReload()147 {148 var messages = new List<string>();149 await Page.GotoAsync(Server.EmptyPage);150 Server.SetRoute("/empty.html", context =>151 {152 messages.Add("route");153 context.Response.ContentType = "text/html";154 return context.Response.WriteAsync("<link rel='stylesheet' href='./one-style.css'>");155 });156 await TaskUtils.WhenAll(157 Page.EvaluateAsync($"window.location.reload();").ContinueWith(_ => messages.Add("evaluate")),158 Page.WaitForNavigationAsync().ContinueWith(_ => messages.Add("navigated")));159 Assert.AreEqual("route|navigated|evaluate", string.Join("|", messages));160 }161 [PlaywrightTest("page-autowaiting-basic.spec.ts", "should await navigating specified target")]162 [Ignore("Flacky")]163 public async Task ShouldAwaitNavigatingSpecifiedTarget()164 {165 var messages = new List<string>();166 Server.SetRoute("/empty.html", context =>167 {168 messages.Add("route");169 context.Response.ContentType = "text/html";170 return context.Response.WriteAsync("<link rel='stylesheet' href='./one-style.css'>");171 });172 await Page.SetContentAsync($@"173 <a href=""{ Server.EmptyPage}"" target=target>empty.html</a>174 <iframe name=target></iframe>");175 var frame = Page.Frame("target");176 await TaskUtils.WhenAll(177 Page.ClickAsync("a").ContinueWith(_ => messages.Add("click")),178 Page.WaitForNavigationAsync().ContinueWith(_ => messages.Add("navigated")));179 Assert.AreEqual(Server.EmptyPage, frame.Url);180 Assert.AreEqual("route|navigated|click", string.Join("|", messages));181 }182 [PlaywrightTest("page-autowaiting-basic.spec.ts", "should work with noWaitAfter: true")]183 public async Task ShouldWorkWithNoWaitAfterTrue()184 {185 Server.SetRoute("/empty.html", _ => Task.CompletedTask);186 await Page.SetContentAsync($"<a id=anchor href='{Server.EmptyPage}'>empty.html</a>");187 await Page.ClickAsync("a", new() { NoWaitAfter = true });188 }189 [PlaywrightTest("page-autowaiting-basic.spec.ts", "should work with waitForLoadState(load)")]190 [Ignore("Flacky")]191 public async Task ShouldWorkWithWaitForLoadStateLoad()192 {193 var messages = new List<string>();194 Server.SetRoute("/empty.html", context =>195 {196 messages.Add("route");197 context.Response.ContentType = "text/html";198 return context.Response.WriteAsync("<link rel='stylesheet' href='./one-style.css'>");199 });200 await Page.SetContentAsync($"<a href=\"{Server.EmptyPage}\">empty.html</a>");201 var clickLoaded = new TaskCompletionSource<bool>();202 await TaskUtils.WhenAll(203 Page.ClickAsync("a").ContinueWith(_ => Page.WaitForLoadStateAsync(LoadState.Load).ContinueWith(_ =>204 {205 messages.Add("clickload");206 clickLoaded.TrySetResult(true);207 })),208 clickLoaded.Task,209 Page.WaitForNavigationAsync(new() { WaitUntil = WaitUntilState.DOMContentLoaded }).ContinueWith(_ => messages.Add("domcontentloaded")));210 Assert.AreEqual("route|domcontentloaded|clickload", string.Join("|", messages));211 }212 [PlaywrightTest("page-autowaiting-basic.spec.ts", "should work with goto following click")]213 public async Task ShouldWorkWithGotoFollowingClick()214 {215 var messages = new List<string>();216 Server.SetRoute("/empty.html", context =>217 {218 messages.Add("route");219 context.Response.ContentType = "text/html";220 return context.Response.WriteAsync("You are logged in");221 });222 await Page.SetContentAsync($@"223 <form action=""{ Server.EmptyPage}/login.html"" method=""get"">...
PageNetworkIdleTests.cs
Source:PageNetworkIdleTests.cs
...58 => NetworkIdleTestAsync(59 Page.MainFrame,60 () =>61 {62 var task = Page.WaitForNavigationAsync(new() { WaitUntil = WaitUntilState.NetworkIdle });63 Page.GotoAsync(Server.Prefix + "/networkidle.html");64 return task;65 });66 [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle in setContent")]67 public async Task ShouldWaitForInSetContent()68 {69 await Page.GotoAsync(Server.EmptyPage);70 await NetworkIdleTestAsync(71 Page.MainFrame,72 () => Page.SetContentAsync("<script src='networkidle.js'></script>", new() { WaitUntil = WaitUntilState.NetworkIdle }),73 true);74 }75 [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle in setContent with request from previous navigation")]76 public async Task ShouldWaitForNetworkIdleInSetContentWithRequestFromPreviousNavigation()77 {78 await Page.GotoAsync(Server.EmptyPage);79 Server.SetRoute("/foo.js", _ => Task.CompletedTask);80 await Page.SetContentAsync("<script>fetch('foo.js')</script>");81 await NetworkIdleTestAsync(82 Page.MainFrame,83 () => Page.SetContentAsync("<script src='networkidle.js'></script>", new() { WaitUntil = WaitUntilState.NetworkIdle }),84 true);85 }86 [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle when navigating iframe")]87 public async Task ShouldWaitForNetworkIdleWhenNavigatingIframe()88 {89 await Page.GotoAsync(Server.Prefix + "/frames/one-frame.html");90 var frame = Page.FirstChildFrame();91 await NetworkIdleTestAsync(92 frame,93 () => frame.GotoAsync(Server.Prefix + "/networkidle.html", new() { WaitUntil = WaitUntilState.NetworkIdle }));94 }95 [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle in setContent from the child frame")]96 public async Task ShouldWaitForInSetContentFromTheChildFrame()97 {98 await Page.GotoAsync(Server.EmptyPage);99 await NetworkIdleTestAsync(100 Page.MainFrame,101 () => Page.SetContentAsync("<iframe src='networkidle.html'></iframe>", new() { WaitUntil = WaitUntilState.NetworkIdle }),102 true);103 }104 [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle from the child frame")]105 public Task ShouldWaitForFromTheChildFrame()106 => NetworkIdleTestAsync(107 Page.MainFrame,108 () => Page.GotoAsync(Server.Prefix + "/networkidle-frame.html", new() { WaitUntil = WaitUntilState.NetworkIdle }));109 [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle from the popup")]110 public async Task ShouldWaitForNetworkIdleFromThePopup()111 {112 await Page.GotoAsync(Server.EmptyPage);113 await Page.SetContentAsync(@"114 <button id=box1 onclick=""window.open('./popup/popup.html')"">Button1</button>115 <button id=box2 onclick=""window.open('./popup/popup.html')"">Button2</button>116 <button id=box3 onclick=""window.open('./popup/popup.html')"">Button3</button>117 <button id=box4 onclick=""window.open('./popup/popup.html')"">Button4</button>118 <button id=box5 onclick=""window.open('./popup/popup.html')"">Button5</button>119 ");120 for (int i = 1; i < 6; i++)121 {122 var popupTask = Page.WaitForPopupAsync();123 await Task.WhenAll(124 Page.WaitForPopupAsync(),125 Page.ClickAsync("#box" + i));126 await popupTask.Result.WaitForLoadStateAsync(LoadState.NetworkIdle);127 }128 }129 private async Task NetworkIdleTestAsync(IFrame frame, Func<Task> action = default, bool isSetContent = false)130 {131 var lastResponseFinished = new Stopwatch();132 var responses = new ConcurrentDictionary<string, TaskCompletionSource<bool>>();133 var fetches = new Dictionary<string, TaskCompletionSource<bool>>();134 async Task RequestDelegate(HttpContext context)135 {136 var taskCompletion = new TaskCompletionSource<bool>();137 responses[context.Request.Path] = taskCompletion;138 fetches[context.Request.Path].TrySetResult(true);139 await taskCompletion.Task;140 lastResponseFinished.Restart();141 context.Response.StatusCode = 404;142 await context.Response.WriteAsync("File not found");143 }144 fetches["/fetch-request-a.js"] = new();145 Server.SetRoute("/fetch-request-a.js", RequestDelegate);146 var firstFetchResourceRequested = Server.WaitForRequest("/fetch-request-a.js");147 fetches["/fetch-request-b.js"] = new();148 Server.SetRoute("/fetch-request-b.js", RequestDelegate);149 var secondFetchResourceRequested = Server.WaitForRequest("/fetch-request-b.js");150 var waitForLoadTask = isSetContent ? Task.CompletedTask : frame.WaitForNavigationAsync(new() { WaitUntil = WaitUntilState.Load });151 var actionTask = action();152 await waitForLoadTask;153 Assert.False(actionTask.IsCompleted);154 await firstFetchResourceRequested;155 Assert.False(actionTask.IsCompleted);156 await fetches["/fetch-request-a.js"].Task;157 await frame.Page.EvaluateAsync("() => window['fetchSecond']()");158 // Finishing first response should leave 2 requests alive and trigger networkidle2.159 responses["/fetch-request-a.js"].TrySetResult(true);160 // Wait for the second round to be requested.161 await secondFetchResourceRequested;162 Assert.False(actionTask.IsCompleted);163 await fetches["/fetch-request-b.js"].Task;164 responses["/fetch-request-b.js"].TrySetResult(true);...
WaitForNavigationAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync();10 var page = await browser.NewPageAsync();11 var frame = page.MainFrame;12 Console.WriteLine($"Request: {request.Url}");13 }14 }15}
WaitForNavigationAsync
Using AI Code Generation
1var playwright = await Playwright.CreateAsync();2var browser = await playwright.Chromium.LaunchAsync(headless: false);3var context = await browser.NewContextAsync();4var page = await context.NewPageAsync();5var frame = page.FirstChildFrame();6await frame.WaitForNavigationAsync();7await page.ScreenshotAsync("google.png");8await browser.CloseAsync();9public virtual Task<IElementHandle> WaitForSelectorAsync(string selector, WaitForSelectorOptions? options = null, CancellationToken cancellationToken = default);10var playwright = await Playwright.CreateAsync();11var browser = await playwright.Chromium.LaunchAsync(headless: false);12var context = await browser.NewContextAsync();13var page = await context.NewPageAsync();14var frame = page.FirstChildFrame();15await page.ScreenshotAsync("google.png");16await browser.CloseAsync();
WaitForNavigationAsync
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions { Headless = false });10 var context = await browser.NewContextAsync();11 var page = await context.NewPageAsync();12 await page.ClickAsync("a[title='Google apps']");13 await page.ClickAsync("text=YouTube");14 await page.ClickAsync("text=Sign in");15 await page.TypeAsync("input[name='identifier']", "
WaitForNavigationAsync
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 var browser = await playwright.Chromium.LaunchAsync();10 var context = await browser.NewContextAsync();11 var page = await context.NewPageAsync();12 var frame = page.Frame("frameId");13 await frame.WaitForNavigationAsync();14 await browser.CloseAsync();15 }16 }17}18using Microsoft.Playwright;19using System;20using System.Threading.Tasks;21{22 {23 static async Task Main(string[] args)24 {25 using var playwright = await Playwright.CreateAsync();26 var browser = await playwright.Chromium.LaunchAsync();27 var context = await browser.NewContextAsync();28 var page = await context.NewPageAsync();29 var frame = page.Frame("frameId");30 var response = await frame.WaitForNavigationAsync();31 await browser.CloseAsync();32 }33 }34}35using Microsoft.Playwright;36using System;37using System.Threading.Tasks;38{39 {40 static async Task Main(string[] args)41 {42 using var playwright = await Playwright.CreateAsync();43 var browser = await playwright.Chromium.LaunchAsync();44 var context = await browser.NewContextAsync();45 var page = await context.NewPageAsync();46 var frame = page.Frame("frameId");47 var response = await frame.WaitForNavigationAsync(new WaitForNavigationOptions { Url = new System.Text.RegularExpressions.Regex(".*") });48 await browser.CloseAsync();49 }50 }51}52using Microsoft.Playwright;53using System;54using System.Threading.Tasks;55{56 {57 static async Task Main(string[] args)58 {59 using var playwright = await Playwright.CreateAsync();
WaitForNavigationAsync
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions10 {11 });12 var context = await browser.NewContextAsync();13 var page = await context.NewPageAsync();14 var navigationTask = page.WaitForNavigationAsync();15 await page.ClickAsync("text=Images");16 await navigationTask;17 await page.ScreenshotAsync("screenshot.png");18 await browser.CloseAsync();19 }20 }21}22using Microsoft.Playwright;23using System;24using System.Threading.Tasks;25{26 {27 static async Task Main(string[] args)28 {29 using var playwright = await Playwright.CreateAsync();30 var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions31 {32 });33 var context = await browser.NewContextAsync();34 var page = await context.NewPageAsync();35 var navigationTask = page.WaitForNavigationAsync();36 await page.ClickAsync("text=Images");37 await navigationTask;38 await page.ScreenshotAsync("screenshot.png");39 await browser.CloseAsync();40 }41 }42}43using Microsoft.Playwright;44using System;45using System.Threading.Tasks;46{47 {48 static async Task Main(string[] args)49 {50 using var playwright = await Playwright.CreateAsync();51 var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions52 {53 });54 var context = await browser.NewContextAsync();55 var page = await context.NewPageAsync();56 var navigationTask = page.WaitForNavigationAsync();57 await page.ClickAsync("text=Images");58 await navigationTask;59 await page.ScreenshotAsync("screenshot.png");60 await browser.CloseAsync();61 }62 }
WaitForNavigationAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync();10 var context = await browser.NewContextAsync();11 var page = await context.NewPageAsync();12 await page.GoToAsync(url);13 await page.WaitForNavigationAsync();14 await page.ScreenshotAsync("google.png");15 }16 }17}18using System;19using System.Threading.Tasks;20using Microsoft.Playwright;21{22 {23 static async Task Main(string[] args)24 {25 using var playwright = await Playwright.CreateAsync();26 await using var browser = await playwright.Chromium.LaunchAsync();27 var context = await browser.NewContextAsync();28 var page = await context.NewPageAsync();29 await page.GoToAsync(url);30 await page.WaitForNavigationAsync(new WaitForNavigationOptions { Timeout = 10000 });31 await page.ScreenshotAsync("google.png");32 }33 }34}35using System;36using System.Threading.Tasks;37using Microsoft.Playwright;38{39 {40 static async Task Main(string[] args)41 {42 using var playwright = await Playwright.CreateAsync();43 await using var browser = await playwright.Chromium.LaunchAsync();44 var context = await browser.NewContextAsync();45 var page = await context.NewPageAsync();46 await page.GoToAsync(url);47 await page.ScreenshotAsync("google.png");48 }49 }50}51using System;52using System.Threading.Tasks;53using Microsoft.Playwright;54{55 {56 static async Task Main(string[] args)57 {
WaitForNavigationAsync
Using AI Code Generation
1await page.ClickAsync("text=Images");2await page.ClickAsync("text=Videos");3await page.ClickAsync("text=News");4await page.ClickAsync("text=Maps");5await page.ClickAsync("text=Shopping");6await page.ClickAsync("text=Gmail");7await page.ClickAsync("text=Drive");8await page.ClickAsync("text=Calendar");9await page.ClickAsync("text=Translate");10await page.ClickAsync("text=More");11await page.ClickAsync("text=Accou
WaitForNavigationAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 await page.TypeAsync("[aria-label='Search']", "Playwright");14 await page.ClickAsync("[aria-label='Google Search']");15 await page.WaitForNavigationAsync();16 await page.ScreenshotAsync("screenshot.png");17 }18 }19}20using System;21using System.Threading.Tasks;22using Microsoft.Playwright;23{24 {25 static async Task Main(string[] args)26 {27 using var playwright = await Playwright.CreateAsync();28 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions29 {30 });31 var page = await browser.NewPageAsync();32 await page.TypeAsync("[aria-label='Search']", "Playwright");33 await page.ClickAsync("[aria-label='Google Search']");34 var navigationTask = page.WaitForNavigationAsync();35 await navigationTask;36 await page.ScreenshotAsync("screenshot.png");37 }38 }39}40using System;41using System.Threading.Tasks;42using Microsoft.Playwright;43{44 {45 static async Task Main(string[] args)46 {
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!