Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.Frame.SetContentAsync
Page.cs
Source:Page.cs
...474 File.WriteAllBytes(options.Path, result);475 }476 return result;477 }478 public Task SetContentAsync(string html, PageSetContentOptions options = default)479 => MainFrame.SetContentAsync(html, new() { WaitUntil = options?.WaitUntil, Timeout = options?.Timeout });480 public Task<string> ContentAsync() => MainFrame.ContentAsync();481 public Task SetExtraHTTPHeadersAsync(IEnumerable<KeyValuePair<string, string>> headers)482 => _channel.SetExtraHTTPHeadersAsync(headers);483 public Task<IElementHandle> QuerySelectorAsync(string selector) => MainFrame.QuerySelectorAsync(selector);484 public Task<IReadOnlyList<IElementHandle>> QuerySelectorAllAsync(string selector)485 => MainFrame.QuerySelectorAllAsync(selector);486 public Task<IJSHandle> EvaluateHandleAsync(string expression, object arg) => MainFrame.EvaluateHandleAsync(expression, arg);487 public Task<IElementHandle> AddScriptTagAsync(PageAddScriptTagOptions options = default)488 => MainFrame.AddScriptTagAsync(new()489 {490 Url = options?.Url,491 Path = options?.Path,492 Content = options?.Content,493 Type = options?.Type,...
PageRouteTests.cs
Source:PageRouteTests.cs
...100 {101 Server.SetRedirect("/rredirect", "/empty.html");102 await Page.GotoAsync(Server.EmptyPage);103 await Page.RouteAsync("**/*", (route) => route.ContinueAsync());104 await Page.SetContentAsync(@"105 <form action='/rredirect' method='post'>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");125 }126 [PlaywrightTest("page-route.spec.ts", "should be able to remove headers")]127 public async Task ShouldBeAbleToRemoveHeaders()128 {129 await Page.RouteAsync("**/*", (route) =>130 {131#pragma warning disable 0612132 var headers = new Dictionary<string, string>(route.Request.Headers.ToDictionary(x => x.Key, x => x.Value)) { ["foo"] = "bar" };133#pragma warning restore 0612134 headers.Remove("origin");135 route.ContinueAsync(new() { Headers = headers });136 });137 var originRequestHeader = Server.WaitForRequest("/empty.html", request => request.Headers["origin"]);138 await TaskUtils.WhenAll(139 originRequestHeader,140 Page.GotoAsync(Server.EmptyPage)141 );142 Assert.AreEqual(StringValues.Empty, originRequestHeader.Result);143 }144 [PlaywrightTest("page-route.spec.ts", "should contain referer header")]145 public async Task ShouldContainRefererHeader()146 {147 var requests = new List<IRequest>();148 await Page.RouteAsync("**/*", (route) =>149 {150 requests.Add(route.Request);151 route.ContinueAsync();152 });153 await Page.GotoAsync(Server.Prefix + "/one-style.html");154 StringAssert.Contains("/one-style.css", requests[1].Url);155#pragma warning disable 0612156 StringAssert.Contains("/one-style.html", requests[1].Headers["referer"]);157#pragma warning restore 0612158 }159 [PlaywrightTest("page-route.spec.ts", "should properly return navigation response when URL has cookies")]160 public async Task ShouldProperlyReturnNavigationResponseWhenURLHasCookies()161 {162 // Setup cookie.163 await Page.GotoAsync(Server.EmptyPage);164 await Context.AddCookiesAsync(new[]165 {166 new Cookie167 {168 Url = Server.EmptyPage,169 Name = "foo",170 Value = "bar"171 }172 });173 // Setup request interception.174 await Page.RouteAsync("**/*", (route) => route.ContinueAsync());175 var response = await Page.ReloadAsync();176 Assert.AreEqual((int)HttpStatusCode.OK, response.Status);177 }178 [PlaywrightTest("page-route.spec.ts", "should show custom HTTP headers")]179 public async Task ShouldShowCustomHTTPHeaders()180 {181 await Page.SetExtraHTTPHeadersAsync(new Dictionary<string, string>182 {183 ["foo"] = "bar"184 });185 await Page.RouteAsync("**/*", (route) =>186 {187#pragma warning disable 0612188 Assert.AreEqual("bar", route.Request.Headers["foo"]);189#pragma warning restore 0612190 route.ContinueAsync();191 });192 var response = await Page.GotoAsync(Server.EmptyPage);193 Assert.True(response.Ok);194 }195 [PlaywrightTest("page-route.spec.ts", "should work with redirect inside sync XHR")]196 public async Task ShouldWorkWithRedirectInsideSyncXHR()197 {198 await Page.GotoAsync(Server.EmptyPage);199 Server.SetRedirect("/logo.png", "/pptr.png");200 await Page.RouteAsync("**/*", (route) => route.ContinueAsync());201 int status = await Page.EvaluateAsync<int>(@"async () => {202 var request = new XMLHttpRequest();203 request.open('GET', '/logo.png', false); // `false` makes the request synchronous204 request.send(null);205 return request.status;206 }");207 Assert.AreEqual(200, status);208 }209 [PlaywrightTest("page-route.spec.ts", "should work with custom referer headers")]210 public async Task ShouldWorkWithCustomRefererHeaders()211 {212 await Page.SetExtraHTTPHeadersAsync(new Dictionary<string, string> { ["referer"] = Server.EmptyPage });213 await Page.RouteAsync("**/*", (route) =>214 {215 if (TestConstants.IsChromium)216 {217#pragma warning disable 0612218 Assert.AreEqual(Server.EmptyPage + ", " + Server.EmptyPage, route.Request.Headers["referer"]);219#pragma warning restore 0612220 }221 else222 {223#pragma warning disable 0612224 Assert.AreEqual(Server.EmptyPage, route.Request.Headers["referer"]);225#pragma warning restore 0612226 }227 route.ContinueAsync();228 });229 var response = await Page.GotoAsync(Server.EmptyPage);230 Assert.True(response.Ok);231 }232 [PlaywrightTest("page-route.spec.ts", "should be abortable")]233 public async Task ShouldBeAbortable()234 {235 await Page.RouteAsync(new Regex("\\.css"), (route) => route.AbortAsync());236 int failedRequests = 0;237 Page.RequestFailed += (_, _) => ++failedRequests;238 var response = await Page.GotoAsync(Server.Prefix + "/one-style.html");239 Assert.True(response.Ok);240 Assert.Null(response.Request.Failure);241 Assert.AreEqual(1, failedRequests);242 }243 [PlaywrightTest("page-route.spec.ts", "should be abortable with custom error codes")]244 public async Task ShouldBeAbortableWithCustomErrorCodes()245 {246 await Page.RouteAsync("**/*", (route) =>247 {248 route.AbortAsync(RequestAbortErrorCode.InternetDisconnected);249 });250 IRequest failedRequest = null;251 Page.RequestFailed += (_, e) => failedRequest = e;252 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.GotoAsync(Server.EmptyPage));253 Assert.NotNull(failedRequest);254 StringAssert.StartsWith(failedRequest.Failure, exception.Message);255 if (TestConstants.IsWebKit)256 {257 Assert.AreEqual("Request intercepted", failedRequest.Failure);258 }259 else if (TestConstants.IsFirefox)260 {261 Assert.AreEqual("NS_ERROR_OFFLINE", failedRequest.Failure);262 }263 else264 {265 Assert.AreEqual("net::ERR_INTERNET_DISCONNECTED", failedRequest.Failure);266 }267 }268 [PlaywrightTest("page-route.spec.ts", "should send referer")]269 public async Task ShouldSendReferer()270 {271 await Page.SetExtraHTTPHeadersAsync(new Dictionary<string, string> { ["referer"] = "http://google.com/" });272 await Page.RouteAsync("**/*", (route) => route.ContinueAsync());273#pragma warning disable 0612274 var requestTask = Server.WaitForRequest("/grid.html", request => request.Headers["referer"]);275#pragma warning restore 0612276 await TaskUtils.WhenAll(277 requestTask,278 Page.GotoAsync(Server.Prefix + "/grid.html")279 );280 Assert.AreEqual("http://google.com/", requestTask.Result);281 }282 [PlaywrightTest("page-route.spec.ts", "should fail navigation when aborting main resource")]283 public async Task ShouldFailNavigationWhenAbortingMainResource()284 {285 await Page.RouteAsync("**/*", (route) => route.AbortAsync());286 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.GotoAsync(Server.EmptyPage));287 Assert.NotNull(exception);288 if (TestConstants.IsWebKit)289 {290 StringAssert.Contains("Request intercepted", exception.Message);291 }292 else if (TestConstants.IsFirefox)293 {294 StringAssert.Contains("NS_ERROR_FAILURE", exception.Message);295 }296 else297 {298 StringAssert.Contains("net::ERR_FAILED", exception.Message);299 }300 }301 [PlaywrightTest("page-route.spec.ts", "should not work with redirects")]302 public async Task ShouldNotWorkWithRedirects()303 {304 var requests = new List<IRequest>();305 await Page.RouteAsync("**/*", (route) =>306 {307 route.ContinueAsync();308 requests.Add(route.Request);309 });310 Server.SetRedirect("/non-existing-page.html", "/non-existing-page-2.html");311 Server.SetRedirect("/non-existing-page-2.html", "/non-existing-page-3.html");312 Server.SetRedirect("/non-existing-page-3.html", "/non-existing-page-4.html");313 Server.SetRedirect("/non-existing-page-4.html", "/empty.html");314 var response = await Page.GotoAsync(Server.Prefix + "/non-existing-page.html");315 StringAssert.Contains("non-existing-page.html", requests[0].Url);316 Assert.That(requests, Has.Count.EqualTo(1));317 Assert.AreEqual("document", requests[0].ResourceType);318 Assert.True(requests[0].IsNavigationRequest);319 var chain = new List<IRequest>();320 for (var request = response.Request; request != null; request = request.RedirectedFrom)321 {322 chain.Add(request);323 Assert.True(request.IsNavigationRequest);324 }325 Assert.AreEqual(5, chain.Count);326 StringAssert.Contains("/empty.html", chain[0].Url);327 StringAssert.Contains("/non-existing-page-4.html", chain[1].Url);328 StringAssert.Contains("/non-existing-page-3.html", chain[2].Url);329 StringAssert.Contains("/non-existing-page-2.html", chain[3].Url);330 StringAssert.Contains("/non-existing-page.html", chain[4].Url);331 for (int i = 0; i < chain.Count; ++i)332 {333 var request = chain[i];334 Assert.True(request.IsNavigationRequest);335 Assert.AreEqual(i > 0 ? chain[i - 1] : null, chain[i].RedirectedTo);336 }337 }338 [PlaywrightTest("page-route.spec.ts", "should work with redirects for subresources")]339 public async Task ShouldWorkWithRedirectsForSubresources()340 {341 var requests = new List<IRequest>();342 await Page.RouteAsync("**/*", (route) =>343 {344 route.ContinueAsync();345 requests.Add(route.Request);346 });347 Server.SetRedirect("/one-style.css", "/two-style.css");348 Server.SetRedirect("/two-style.css", "/three-style.css");349 Server.SetRedirect("/three-style.css", "/four-style.css");350 Server.SetRoute("/four-style.css", context => context.Response.WriteAsync("body {box-sizing: border-box; }"));351 var response = await Page.GotoAsync(Server.Prefix + "/one-style.html");352 Assert.AreEqual((int)HttpStatusCode.OK, response.Status);353 StringAssert.Contains("one-style.html", response.Url);354 Assert.AreEqual(2, requests.Count);355 Assert.AreEqual("document", requests[0].ResourceType);356 StringAssert.Contains("one-style.html", requests[0].Url);357 var request = requests[1];358 foreach (string url in new[] { "/one-style.css", "/two-style.css", "/three-style.css", "/four-style.css" })359 {360 Assert.AreEqual("stylesheet", request.ResourceType);361 StringAssert.Contains(url, request.Url);362 request = request.RedirectedTo;363 }364 Assert.Null(request);365 }366 [PlaywrightTest("page-route.spec.ts", "should work with equal requests")]367 public async Task ShouldWorkWithEqualRequests()368 {369 await Page.GotoAsync(Server.EmptyPage);370 int responseCount = 1;371 Server.SetRoute("/zzz", context => context.Response.WriteAsync((responseCount++ * 11).ToString()));372 bool spinner = false;373 // Cancel 2nd request.374 await Page.RouteAsync("**/*", (route) =>375 {376 if (spinner)377 {378 _ = route.AbortAsync();379 }380 else381 {382 _ = route.ContinueAsync();383 }384 spinner = !spinner;385 });386 var results = new List<string>();387 for (int i = 0; i < 3; ++i)388 {389 results.Add(await Page.EvaluateAsync<string>("fetch('/zzz').then(response => response.text()).catch (e => 'FAILED')"));390 }391 Assert.AreEqual(new[] { "11", "FAILED", "22" }, results);392 }393 [PlaywrightTest("page-route.spec.ts", "should navigate to dataURL and not fire dataURL requests")]394 public async Task ShouldNavigateToDataURLAndNotFireDataURLRequests()395 {396 var requests = new List<IRequest>();397 await Page.RouteAsync("**/*", (route) =>398 {399 requests.Add(route.Request);400 route.ContinueAsync();401 });402 string dataURL = "data:text/html,<div>yo</div>";403 var response = await Page.GotoAsync(dataURL);404 Assert.Null(response);405 Assert.IsEmpty(requests);406 }407 [PlaywrightTest("page-route.spec.ts", "should be able to fetch dataURL and not fire dataURL requests")]408 public async Task ShouldBeAbleToFetchDataURLAndNotFireDataURLRequests()409 {410 await Page.GotoAsync(Server.EmptyPage);411 var requests = new List<IRequest>();412 await Page.RouteAsync("**/*", (route) =>413 {414 requests.Add(route.Request);415 route.ContinueAsync();416 });417 string dataURL = "data:text/html,<div>yo</div>";418 string text = await Page.EvaluateAsync<string>("url => fetch(url).then(r => r.text())", dataURL);419 Assert.AreEqual("<div>yo</div>", text);420 Assert.IsEmpty(requests);421 }422 [PlaywrightTest("page-route.spec.ts", "should navigate to URL with hash and and fire requests without hash")]423 public async Task ShouldNavigateToURLWithHashAndAndFireRequestsWithoutHash()424 {425 var requests = new List<IRequest>();426 await Page.RouteAsync("**/*", (route) =>427 {428 requests.Add(route.Request);429 route.ContinueAsync();430 });431 var response = await Page.GotoAsync(Server.EmptyPage + "#hash");432 Assert.AreEqual((int)HttpStatusCode.OK, response.Status);433 Assert.AreEqual(Server.EmptyPage, response.Url);434 Assert.That(requests, Has.Count.EqualTo(1));435 Assert.AreEqual(Server.EmptyPage, requests[0].Url);436 }437 [PlaywrightTest("page-route.spec.ts", "should work with encoded server")]438 public async Task ShouldWorkWithEncodedServer()439 {440 // The requestWillBeSent will report encoded URL, whereas interception will441 // report URL as-is. @see crbug.com/759388442 await Page.RouteAsync("**/*", (route) => route.ContinueAsync());443 var response = await Page.GotoAsync(Server.Prefix + "/some nonexisting page");444 Assert.AreEqual((int)HttpStatusCode.NotFound, response.Status);445 }446 [PlaywrightTest("page-route.spec.ts", "should work with badly encoded server")]447 public async Task ShouldWorkWithBadlyEncodedServer()448 {449 Server.SetRoute("/malformed?rnd=%911", _ => Task.CompletedTask);450 await Page.RouteAsync("**/*", (route) => route.ContinueAsync());451 var response = await Page.GotoAsync(Server.Prefix + "/malformed?rnd=%911");452 Assert.AreEqual((int)HttpStatusCode.OK, response.Status);453 }454 [PlaywrightTest("page-route.spec.ts", "should work with encoded server - 2")]455 public async Task ShouldWorkWithEncodedServer2()456 {457 // The requestWillBeSent will report URL as-is, whereas interception will458 // report encoded URL for stylesheet. @see crbug.com/759388459 var requests = new List<IRequest>();460 await Page.RouteAsync("**/*", (route) =>461 {462 route.ContinueAsync();463 requests.Add(route.Request);464 });465 var response = await Page.GotoAsync($"data:text/html,<link rel=\"stylesheet\" href=\"{Server.EmptyPage}/fonts?helvetica|arial\"/>");466 Assert.Null(response);467 // TODO: https://github.com/microsoft/playwright/issues/12789468 if (TestConstants.IsFirefox)469 Assert.That(requests, Has.Count.EqualTo(2));470 else471 Assert.That(requests, Has.Count.EqualTo(1));472 Assert.AreEqual((int)HttpStatusCode.NotFound, (await requests[0].ResponseAsync()).Status);473 }474 [PlaywrightTest("page-route.spec.ts", @"should not throw ""Invalid Interception Id"" if the request was cancelled")]475 public async Task ShouldNotThrowInvalidInterceptionIdIfTheRequestWasCancelled()476 {477 await Page.SetContentAsync("<iframe></iframe>");478 IRoute route = null;479 await Page.RouteAsync("**/*", (r) => route = r);480 _ = Page.EvalOnSelectorAsync("iframe", "(frame, url) => frame.src = url", Server.EmptyPage);481 // Wait for request interception.482 await Page.WaitForRequestAsync("**/*");483 // Delete frame to cause request to be canceled.484 await Page.EvalOnSelectorAsync("iframe", "frame => frame.remove()");485 await route.ContinueAsync();486 }487 [PlaywrightTest("page-route.spec.ts", "should intercept main resource during cross-process navigation")]488 public async Task ShouldInterceptMainResourceDuringCrossProcessNavigation()489 {490 await Page.GotoAsync(Server.EmptyPage);491 bool intercepted = false;...
Frame.cs
Source:Frame.cs
...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(...
PageNetworkRequestTest.cs
Source:PageNetworkRequestTest.cs
...143 await Page.GotoAsync(Server.EmptyPage);144 Server.SetRoute("/post", _ => Task.CompletedTask);145 IRequest request = null;146 Page.Request += (_, e) => request = e;147 await Page.SetContentAsync("<form method='POST' action='/post'><input type='text' name='foo' value='bar'><input type='number' name='baz' value='123'><input type='submit'></form>");148 await Page.ClickAsync("input[type=submit]");149 Assert.NotNull(request);150 var element = request.PostDataJSON();151 Assert.AreEqual("bar", element?.GetProperty("foo").ToString());152 Assert.AreEqual("123", element?.GetProperty("baz").ToString());153 }154 [PlaywrightTest("page-network-request.spec.ts", "should be |undefined| when there is no post data")]155 public async Task ShouldBeUndefinedWhenThereIsNoPostData2()156 {157 var response = await Page.GotoAsync(Server.EmptyPage);158 Assert.Null(response.Request.PostDataJSON());159 }160 [PlaywrightTest("page-network-request.spec.ts", "should return event source")]161 public async Task ShouldReturnEventSource()...
DefaultBrowserContext1Tests.cs
Source:DefaultBrowserContext1Tests.cs
...259 context.Response.Headers["Content-Type"] = "application/octet-stream";260 context.Response.Headers["Content-Disposition"] = "attachment";261 return context.Response.WriteAsync("Hello world");262 });263 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");264 var downloadTask = page.WaitForDownloadAsync();265 await TaskUtils.WhenAll(266 downloadTask,267 page.ClickAsync("a"));268 var download = downloadTask.Result;269 var path = await download.PathAsync();270 Assert.AreEqual(File.Exists(path), true);271 Assert.AreEqual(File.ReadAllText(path), "Hello world");272 }273 private async Task<(TempDirectory tmp, IBrowserContext context, IPage page)> LaunchPersistentAsync(BrowserTypeLaunchPersistentContextOptions options = null)274 {275 var tmp = new TempDirectory();276 var context = await BrowserType.LaunchPersistentContextAsync(277 tmp.Path,...
PageAutoWaitingBasicTests.cs
Source:PageAutoWaitingBasicTests.cs
...40 messages.Add("route");41 context.Response.ContentType = "text/html";42 return context.Response.WriteAsync("<link rel='stylesheet' href='./one-style.css'>");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"">224 <input type=""text"">225 <input type=""submit"" value=""Submit"">226 </form>");227 await Page.FillAsync("input[type=text]", "admin");228 await Page.ClickAsync("input[type=submit]");229 await Page.GotoAsync(Server.EmptyPage);230 }231 }232}...
PageNetworkIdleTests.cs
Source:PageNetworkIdleTests.cs
...49 public async Task ShouldWaitForToSucceedNavigationWithRequestFromPreviousNavigation()50 {51 await Page.GotoAsync(Server.EmptyPage);52 Server.SetRoute("/foo.js", _ => Task.CompletedTask);53 await Page.SetContentAsync("<script>fetch('foo.js')</script>");54 await NetworkIdleTestAsync(Page.MainFrame, () => Page.GotoAsync(Server.Prefix + "/networkidle.html", new() { WaitUntil = WaitUntilState.NetworkIdle }));55 }56 [PlaywrightTest("page-network-idle.spec.ts", "should wait for networkidle in waitForNavigation")]57 public Task ShouldWaitForInWaitForNavigation()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 }...
PageWaitForUrlTests.cs
Source:PageWaitForUrlTests.cs
...74 [PlaywrightTest("page-wait-for-url.spec.ts", "should work with clicking on anchor links")]75 public async Task ShouldWorkWithClickingOnAnchorLinks()76 {77 await Page.GotoAsync(Server.EmptyPage);78 await Page.SetContentAsync("<a href='#foobar'>foobar</a>");79 await Page.ClickAsync("a");80 await Page.WaitForURLAsync("**/*#foobar");81 }82 [PlaywrightTest("page-wait-for-url.spec.ts", "should work with history.pushState()")]83 public async Task ShouldWorkWithHistoryPushState()84 {85 await Page.GotoAsync(Server.EmptyPage);86 await Page.SetContentAsync(@"87 <a onclick='javascript:replaceState()'>SPA</a>88 <script>89 function replaceState() { history.replaceState({}, '', '/replaced.html') }90 </script>91 ");92 await Page.ClickAsync("a");93 await Page.WaitForURLAsync("**/replaced.html");94 Assert.AreEqual(Server.Prefix + "/replaced.html", Page.Url);95 }96 [PlaywrightTest("page-wait-for-url.spec.ts", "should work with DOM history.back()/history.forward()")]97 public async Task ShouldWorkWithDOMHistoryBackHistoryForward()98 {99 await Page.GotoAsync(Server.EmptyPage);100 await Page.SetContentAsync(@"101 <a id=back onclick='javascript:goBack()'>back</a>102 <a id=forward onclick='javascript:goForward()'>forward</a>103 <script>104 function goBack() { history.back(); }105 function goForward() { history.forward(); }106 history.pushState({}, '', '/first.html');107 history.pushState({}, '', '/second.html');108 </script>109 ");110 Assert.AreEqual(Server.Prefix + "/second.html", Page.Url);111 await Task.WhenAll(Page.WaitForURLAsync("**/first.html"), Page.ClickAsync("a#back"));112 Assert.AreEqual(Server.Prefix + "/first.html", Page.Url);113 await Task.WhenAll(Page.WaitForURLAsync("**/second.html"), Page.ClickAsync("a#forward"));114 Assert.AreEqual(Server.Prefix + "/second.html", Page.Url);...
SetContentAsync
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(headless: false);10 var page = await browser.NewPageAsync();11 await page.SetContentAsync("<html><body><h1>hello world</h1></body></html>");12 }13 }14}15using Microsoft.Playwright;16using System;17using System.Threading.Tasks;18{19 {20 static async Task Main(string[] args)21 {22 using var playwright = await Playwright.CreateAsync();23 var browser = await playwright.Chromium.LaunchAsync(headless: false);24 var page = await browser.NewPageAsync();25 var element = await page.QuerySelectorAsync("input");26 await element.TypeAsync("hello world");27 }28 }29}30using Microsoft.Playwright;31using System;32using System.Threading.Tasks;33{34 {35 static async Task Main(string[] args)36 {37 using var playwright = await Playwright.CreateAsync();38 var browser = await playwright.Chromium.LaunchAsync(headless: false);39 var page = await browser.NewPageAsync();
SetContentAsync
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 BrowserTypeLaunchOptions10 {11 });12 var context = await browser.NewContextAsync();13 var page = await context.NewPageAsync();14 await page.SetContentAsync("<html><body><h1>My Page</h1></body></html>");15 await page.ScreenshotAsync("2.png");16 await browser.CloseAsync();17 }18 }19}20Microsoft.Playwright.Core.Frame.SetContentAsync Method (String, SetContentOptions)21Playwright: Set Content (HTML)22Playwright: Set Content (HTML, Options)23Playwright: Set Content (HTML, Options) (WaitUntil)24Playwright: Set Content (HTML, Options) (WaitUntil, Timeout)25Playwright: Set Content (HTML, Options) (WaitUntil, Timeout, WaitForLoadState)26Playwright: Set Content (HTML, Options) (WaitUntil, Timeout, WaitForLoadState,
SetContentAsync
Using AI Code Generation
1using Microsoft.Playwright;2using Microsoft.Playwright.Core;3using System;4using System.Threading.Tasks;5{6 {7 static async Task Main(string[] args)8 {9 await using var playwright = await Playwright.CreateAsync();10 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions11 {12 });13 var page = await browser.NewPageAsync();14 await page.SetContentAsync("<html><body><h1>First heading</h1><p>First paragraph.</p></body></html>");
SetContentAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Playwright.Core;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 await page.SetContentAsync(@"<html><head></head><body><h1>Hello World!</h1></body></html>");12 await page.ScreenshotAsync("2.png");13 }14 }15}
SetContentAsync
Using AI Code Generation
1var playwright = await Playwright.CreateAsync();2var browser = await playwright.Chromium.LaunchAsync();3var page = await browser.NewPageAsync();4await page.SetContentAsync("<html><body><h1>Hi</h1></body></html>");5await page.ScreenshotAsync("screenshot.png");6await browser.CloseAsync();7var playwright = await Playwright.CreateAsync();8var browser = await playwright.Chromium.LaunchAsync();9var page = await browser.NewPageAsync();10await page.SetContentAsync("<html><body><h1>Hi</h1></body></html>");11await page.ScreenshotAsync("screenshot.png");12await browser.CloseAsync();13var playwright = await Playwright.CreateAsync();14var browser = await playwright.Chromium.LaunchAsync();15var page = await browser.NewPageAsync();16await page.SetContentAsync("<html><body><h1>Hi</h1></body></html>");17await page.ScreenshotAsync("screenshot.png");18await browser.CloseAsync();19var playwright = await Playwright.CreateAsync();20var browser = await playwright.Chromium.LaunchAsync();21var page = await browser.NewPageAsync();22await page.SetContentAsync("<html><body><h1>Hi</h1></body></html>");23await page.ScreenshotAsync("screenshot.png");24await browser.CloseAsync();25var playwright = await Playwright.CreateAsync();26var browser = await playwright.Chromium.LaunchAsync();27var page = await browser.NewPageAsync();28await page.SetContentAsync("<html><body><h1>Hi</h1></body></html>");29await page.ScreenshotAsync("screenshot.png");30await browser.CloseAsync();
SetContentAsync
Using AI Code Generation
1var frame = await Page.QuerySelectorAsync("iframe").EvaluateAsync<Microsoft.Playwright.Core.Frame>("e => e.contentDocument.defaultView.frameElement");2await frame.SetContentAsync("<html><body><h1>Set Content of Frame</h1></body></html>");3var frame = await Page.QuerySelectorAsync("iframe").EvaluateAsync<Microsoft.Playwright.Core.Frame>("e => e.contentDocument.defaultView.frameElement");4await frame.SetContentAsync("<html><body><h1>Set Content of Frame</h1></body></html>");5var frame = await Page.QuerySelectorAsync("iframe").EvaluateAsync<Microsoft.Playwright.Core.Frame>("e => e.contentDocument.defaultView.frameElement");6await frame.SetContentAsync("<html><body><h1>Set Content of Frame</h1></body></html>");7var frame = await Page.QuerySelectorAsync("iframe").EvaluateAsync<Microsoft.Playwright.Core.Frame>("e => e.contentDocument.defaultView.frameElement");8await frame.SetContentAsync("<html><body><h1>Set Content of Frame</h1></body></html>");9var frame = await Page.QuerySelectorAsync("iframe").EvaluateAsync<Microsoft.Playwright.Core.Frame>("e => e.contentDocument.defaultView.frameElement");10await frame.SetContentAsync("<html><body><h1>Set Content of Frame</h1></body></html>");11var frame = await Page.QuerySelectorAsync("iframe").EvaluateAsync<Microsoft.Playwright.Core.Frame>("e => e.contentDocument.defaultView.frameElement");
SetContentAsync
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();10 var page = await browser.NewPageAsync();11 await page.SetContentAsync("<html><body><h1>Playwright .NET</h1></body></html>");12 await page.ScreenshotAsync(path: "screenshot.png");13 }14 }15}16using Microsoft.Playwright;17using System;18using System.Threading.Tasks;19{20 {21 static async Task Main(string[] args)22 {23 using var playwright = await Playwright.CreateAsync();24 await using var browser = await playwright.Chromium.LaunchAsync();25 var page = await browser.NewPageAsync();26 await page.SetContentAsync("<html><body><h1>Playwright .NET</h1></body></html>");27 await page.ScreenshotAsync(path: "screenshot.png");28 }29 }30}31using Microsoft.Playwright;32using System;33using System.Threading.Tasks;34{35 {36 static async Task Main(string[] args)37 {38 using var playwright = await Playwright.CreateAsync();
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!!