How to use EvaluateAsync method of Microsoft.Playwright.Core.Frame class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.Frame.EvaluateAsync

PageRouteTests.cs

Source:PageRouteTests.cs Github

copy

Full Screen

...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;492 await Page.RouteAsync(Server.CrossProcessPrefix + "/empty.html", (route) =>493 {494 if (route.Request.Url.Contains(Server.CrossProcessPrefix + "/empty.html"))495 {496 intercepted = true;497 }498 route.ContinueAsync();499 });500 var response = await Page.GotoAsync(Server.CrossProcessPrefix + "/empty.html");501 Assert.True(response.Ok);502 Assert.True(intercepted);503 }504 [PlaywrightTest("page-route.spec.ts", "should fulfill with redirect status")]505 [Skip(SkipAttribute.Targets.Webkit)]506 public async Task ShouldFulfillWithRedirectStatus()507 {508 await Page.GotoAsync(Server.Prefix + "/title.html");509 Server.SetRoute("/final", context => context.Response.WriteAsync("foo"));510 await Page.RouteAsync("**/*", (route) =>511 {512 if (route.Request.Url != Server.Prefix + "/redirect_this")513 {514 route.ContinueAsync();515 return;516 }517 _ = route.FulfillAsync(new()518 {519 Status = (int)HttpStatusCode.MovedPermanently,520 Headers = new Dictionary<string, string>521 {522 ["location"] = "/final",523 }524 });525 });526 string text = await Page.EvaluateAsync<string>(@"async url => {527 const data = await fetch(url);528 return data.text();529 }", Server.Prefix + "/redirect_this");530 Assert.AreEqual("foo", text);531 }532 [PlaywrightTest("page-route.spec.ts", "should support cors with GET")]533 public async Task ShouldSupportCorsWithGET()534 {535 await Page.GotoAsync(Server.EmptyPage);536 await Page.RouteAsync("**/cars*", (route) =>537 {538 var headers = new Dictionary<string, string>() { ["access-control-allow-origin"] = route.Request.Url.EndsWith("allow") ? "*" : "none" };539 _ = route.FulfillAsync(new()540 {541 ContentType = "application/json",542 Headers = headers,543 Status = (int)HttpStatusCode.OK,544 Body = "[\"electric\", \"cars\"]"545 });546 });547 string[] resp = await Page.EvaluateAsync<string[]>(@"async () => {548 const response = await fetch('https://example.com/cars?allow', { mode: 'cors' });549 return response.json();550 }");551 Assert.AreEqual(new[] { "electric", "cars" }, resp);552 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.EvaluateAsync<string[]>(@"async () => {553 const response = await fetch('https://example.com/cars?reject', { mode: 'cors' });554 return response.json();555 }"));556 if (TestConstants.IsChromium)557 StringAssert.Contains("Failed", exception.Message);558 else if (TestConstants.IsWebKit)559 StringAssert.Contains("TypeError", exception.Message);560 else if (TestConstants.IsFirefox)561 StringAssert.Contains("NetworkError", exception.Message);562 else563 Assert.Fail("Unknown browser type.");564 }565 [PlaywrightTest("page-route.spec.ts", "should support cors with POST")]566 public async Task ShouldSupportCorsWithPOST()567 {568 await Page.GotoAsync(Server.EmptyPage);569 await Page.RouteAsync("**/cars*", (route) =>570 {571 _ = route.FulfillAsync(new()572 {573 ContentType = "application/json",574 Headers = new Dictionary<string, string> { ["access-control-allow-origin"] = "*" },575 Status = (int)HttpStatusCode.OK,576 Body = "[\"electric\", \"cars\"]"577 });578 });579 string[] resp = await Page.EvaluateAsync<string[]>(@"async () => {580 const response = await fetch('https://example.com/cars', {581 method: 'POST',582 headers: { 'Content-Type': 'application/json' },583 mode: 'cors',584 body: JSON.stringify({ 'number': 1 }) 585 });586 return response.json();587 }");588 Assert.AreEqual(new[] { "electric", "cars" }, resp);589 }590 [PlaywrightTest("page-route.spec.ts", "should support cors with different methods")]591 public async Task ShouldSupportCorsWithDifferentMethods()592 {593 await Page.GotoAsync(Server.EmptyPage);594 await Page.RouteAsync("**/cars*", (route) =>595 {596 _ = route.FulfillAsync(new()597 {598 ContentType = "application/json",599 Headers = new Dictionary<string, string> { ["access-control-allow-origin"] = "*" },600 Status = (int)HttpStatusCode.OK,601 Body = $"[\"{ route.Request.Method.ToString().ToUpper() }\", \"electric\", \"cars\"]"602 });603 });604 string[] resp = await Page.EvaluateAsync<string[]>(@"async () => {605 const response = await fetch('https://example.com/cars', {606 method: 'POST',607 headers: { 'Content-Type': 'application/json' },608 mode: 'cors',609 body: JSON.stringify({ 'number': 1 }) 610 });611 return response.json();612 }");613 Assert.AreEqual(new[] { "POST", "electric", "cars" }, resp);614 resp = await Page.EvaluateAsync<string[]>(@"async () => {615 const response = await fetch('https://example.com/cars', {616 method: 'DELETE',617 headers: { 'Content-Type': 'application/json' },618 mode: 'cors',619 body: JSON.stringify({ 'number': 1 }) 620 });621 return response.json();622 }");623 Assert.AreEqual(new[] { "DELETE", "electric", "cars" }, resp);624 }625 [PlaywrightTest]626 public void ShouldThrowOnInvalidRouteUrl()627 {628#if NETCOREAPP3_1...

Full Screen

Full Screen

PageNetworkRequestTest.cs

Source:PageNetworkRequestTest.cs Github

copy

Full Screen

...56 {57 await Page.GotoAsync(Server.EmptyPage);58 var requests = new List<IRequest>();59 Page.Request += (_, e) => requests.Add(e);60 await Page.EvaluateAsync("fetch('/digits/1.png')");61 Assert.AreEqual(1, requests.Where(r => !r.Url.Contains("favicon")).Count());62 Assert.AreEqual(Page.MainFrame, requests[0].Frame);63 }64 [PlaywrightTest("page-network-request.spec.ts", "should return headers")]65 public async Task ShouldReturnHeaders()66 {67 var response = await Page.GotoAsync(Server.EmptyPage);68 string expected = TestConstants.BrowserName switch69 {70 "chromium" => "Chrome",71 "firefox" => "Firefox",72 "webkit" => "WebKit",73 _ => "None"74 };75#pragma warning disable 061276 StringAssert.Contains(expected, response.Request.Headers["user-agent"]);77#pragma warning restore 061278 }79 [PlaywrightTest("page-network-request.spec.ts", "should return postData")]80 public async Task ShouldReturnPostData()81 {82 await Page.GotoAsync(Server.EmptyPage);83 Server.SetRoute("/post", _ => Task.CompletedTask);84 IRequest request = null;85 Page.Request += (_, e) => request = e;86 await Page.EvaluateHandleAsync("fetch('./post', { method: 'POST', body: JSON.stringify({ foo: 'bar'})})");87 Assert.NotNull(request);88 Assert.AreEqual("{\"foo\":\"bar\"}", request.PostData);89 }90 [PlaywrightTest("page-network-request.spec.ts", "should work with binary post data")]91 public async Task ShouldWorkWithBinaryPostData()92 {93 await Page.GotoAsync(Server.EmptyPage);94 Server.SetRoute("/post", _ => Task.CompletedTask);95 IRequest request = null;96 Page.Request += (_, e) => request = e;97 await Page.EvaluateHandleAsync("fetch('./post', { method: 'POST', body: new Uint8Array(Array.from(Array(256).keys())) })");98 Assert.NotNull(request);99 byte[] data = request.PostDataBuffer;100 Assert.AreEqual(256, data.Length);101 for (int index = 0; index < data.Length; index++)102 {103 Assert.AreEqual(index, data[index]);104 }105 }106 [PlaywrightTest("page-network-request.spec.ts", "should work with binary post data and interception")]107 public async Task ShouldWorkWithBinaryPostDataAndInterception()108 {109 await Page.GotoAsync(Server.EmptyPage);110 Server.SetRoute("/post", _ => Task.CompletedTask);111 await Page.RouteAsync("/post", (route) => route.ContinueAsync());112 IRequest request = null;113 Page.Request += (_, e) => request = e;114 await Page.EvaluateHandleAsync("fetch('./post', { method: 'POST', body: new Uint8Array(Array.from(Array(256).keys())) })");115 Assert.NotNull(request);116 byte[] data = request.PostDataBuffer;117 Assert.AreEqual(256, data.Length);118 for (int index = 0; index < data.Length; index++)119 {120 Assert.AreEqual(index, data[index]);121 }122 }123 [PlaywrightTest("page-network-request.spec.ts", "should be |undefined| when there is no post data")]124 public async Task ShouldBeUndefinedWhenThereIsNoPostData()125 {126 var response = await Page.GotoAsync(Server.EmptyPage);127 Assert.Null(response.Request.PostData);128 }129 [PlaywrightTest("page-network-request.spec.ts", "should parse the json post data")]130 public async Task ShouldParseTheJsonPostData()131 {132 await Page.GotoAsync(Server.EmptyPage);133 Server.SetRoute("/post", _ => Task.CompletedTask);134 IRequest request = null;135 Page.Request += (_, e) => request = e;136 await Page.EvaluateHandleAsync("fetch('./post', { method: 'POST', body: JSON.stringify({ foo: 'bar'})})");137 Assert.NotNull(request);138 Assert.AreEqual("bar", request.PostDataJSON()?.GetProperty("foo").ToString());139 }140 [PlaywrightTest("page-network-request.spec.ts", "should parse the data if content-type is application/x-www-form-urlencoded")]141 public async Task ShouldParseTheDataIfContentTypeIsApplicationXWwwFormUrlencoded()142 {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()162 {163 const string sseMessage = "{\"foo\": \"bar\"}";164 Server.SetRoute("/sse", async ctx =>165 {166 ctx.Response.Headers["content-type"] = "text/event-stream";167 ctx.Response.Headers["connection"] = "keep-alive";168 ctx.Response.Headers["cache-control"] = "no-cache";169 await ctx.Response.Body.FlushAsync();170 await ctx.Response.WriteAsync($"data: {sseMessage}\r\r");171 await ctx.Response.Body.FlushAsync();172 });173 await Page.GotoAsync(Server.EmptyPage);174 var requests = new List<IRequest>();175 Page.Request += (_, e) => requests.Add(e);176 Assert.AreEqual(sseMessage, await Page.EvaluateAsync<string>(@"() => {177 const eventSource = new EventSource('/sse');178 return new Promise(resolve => {179 eventSource.onmessage = e => resolve(e.data);180 });181 }"));182 Assert.AreEqual("eventsource", requests[0].ResourceType);183 }184 [PlaywrightTest("page-network-request.spec.ts", "should return navigation bit")]185 public async Task ShouldReturnNavigationBit()186 {187 var requests = new Dictionary<string, IRequest>();188 Page.Request += (_, e) => requests[e.Url.Split('/').Last()] = e;189 Server.SetRedirect("/rrredirect", "/frames/one-frame.html");190 await Page.GotoAsync(Server.Prefix + "/rrredirect");191 Assert.True(requests["rrredirect"].IsNavigationRequest);192 Assert.True(requests["one-frame.html"].IsNavigationRequest);193 Assert.True(requests["frame.html"].IsNavigationRequest);194 Assert.False(requests["script.js"].IsNavigationRequest);195 Assert.False(requests["style.css"].IsNavigationRequest);196 }197 [PlaywrightTest("page-network-request.spec.ts", "Request.isNavigationRequest", "should return navigation bit when navigating to image")]198 public async Task ShouldReturnNavigationBitWhenNavigatingToImage()199 {200 var requests = new List<IRequest>();201 Page.Request += (_, e) => requests.Add(e);202 await Page.GotoAsync(Server.Prefix + "/pptr.png");203 Assert.True(requests[0].IsNavigationRequest);204 }205 [PlaywrightTest("page-network-request.spec.ts", "should set bodySize and headersSize")]206 public async Task ShouldSetBodySizeAndHeaderSize()207 {208 await Page.GotoAsync(Server.EmptyPage);209 var tsc = new TaskCompletionSource<RequestSizesResult>();210 Page.Request += async (sender, r) =>211 {212 await (await r.ResponseAsync()).FinishedAsync();213 tsc.SetResult(await r.SizesAsync());214 };215 await Page.EvaluateAsync("() => fetch('./get', { method: 'POST', body: '12345'}).then(r => r.text())");216 var sizes = await tsc.Task;217 Assert.AreEqual(5, sizes.RequestBodySize);218 Assert.GreaterOrEqual(sizes.RequestHeadersSize, 200);219 }220 [PlaywrightTest("page-network-request.spec.ts", "should should set bodySize to 0 if there was no body")]221 public async Task ShouldSetBodysizeTo0IfThereWasNoBody()222 {223 await Page.GotoAsync(Server.EmptyPage);224 var tsc = new TaskCompletionSource<RequestSizesResult>();225 Page.Request += async (sender, r) =>226 {227 await (await r.ResponseAsync()).FinishedAsync();228 tsc.SetResult(await r.SizesAsync());229 };230 await Page.EvaluateAsync("() => fetch('./get').then(r => r.text())");231 var sizes = await tsc.Task;232 Assert.AreEqual(0, sizes.RequestBodySize);233 Assert.GreaterOrEqual(sizes.RequestHeadersSize, 200);234 }235 [PlaywrightTest("page-network-request.spec.ts", "should should set bodySize, headersSize, and transferSize")]236 [Skip(SkipAttribute.Targets.Firefox, SkipAttribute.Targets.Chromium, SkipAttribute.Targets.Webkit)]237 public async Task ShouldSetAllTheResponseSizes()238 {239 Server.SetRoute("/get", async ctx =>240 {241 ctx.Response.Headers["Content-Type"] = "text/plain; charset=utf-8";242 await ctx.Response.WriteAsync("abc134");243 await ctx.Response.CompleteAsync();244 });245 await Page.GotoAsync(Server.EmptyPage);246 var tsc = new TaskCompletionSource<RequestSizesResult>();247 Page.Request += async (sender, r) =>248 {249 await (await r.ResponseAsync()).FinishedAsync();250 tsc.SetResult(await r.SizesAsync());251 };252 var message = await Page.EvaluateAsync<string>("() => fetch('./get').then(r => r.arrayBuffer()).then(b => b.bufferLength)");253 var sizes = await tsc.Task;254 Assert.AreEqual(6, sizes.ResponseBodySize);255 Assert.GreaterOrEqual(sizes.ResponseHeadersSize, 142);256 }257 [PlaywrightTest("page-network-request.spec.ts", "should should set bodySize to 0 when there was no response body")]258 public async Task ShouldSetBodySizeTo0WhenNoResponseBody()259 {260 var response = await Page.GotoAsync(Server.EmptyPage);261 await response.FinishedAsync();262 var sizes = await response.Request.SizesAsync();263 Assert.AreEqual(0, sizes.ResponseBodySize);264 Assert.GreaterOrEqual(sizes.ResponseHeadersSize, 142);265 }266 [PlaywrightTest("page-network-request.spec.ts", "should report raw headers")]267 public async Task ShouldReportRawHeaders()268 {269 var expectedHeaders = new Dictionary<string, string>();270 Server.SetRoute("/headers", async ctx =>271 {272 expectedHeaders.Clear();273 foreach (var header in ctx.Request.Headers)274 {275 expectedHeaders.Add(header.Key.ToLower(), header.Value);276 }277 await ctx.Response.CompleteAsync();278 });279 await Page.GotoAsync(Server.EmptyPage);280 //Page.RunAndWaitForRequestFinishedAsync(281 // async () => await Page.EvaluateAsync("**/*")282 var requestTask = Page.WaitForRequestAsync("**/*");283 var evalTask = Page.EvaluateAsync(@"() =>284fetch('/headers', {285 headers: [286 ['header-a', 'value-a'],287 ['header-b', 'value-b'],288 ['header-a', 'value-a-1'],289 ['header-a', 'value-a-2'],290 ]291 })292");293 await Task.WhenAll(requestTask, evalTask);294 var req = requestTask.Result;295 Assert.AreEqual("value-a, value-a-1, value-a-2", await req.HeaderValueAsync("header-a"));296 Assert.IsNull(await req.HeaderValueAsync("not-there"));297 }...

Full Screen

Full Screen

BrowserContextBasicTests.cs

Source:BrowserContextBasicTests.cs Github

copy

Full Screen

...54 var popupTargetCompletion = new TaskCompletionSource<IPage>();55 page.Popup += (_, e) => popupTargetCompletion.SetResult(e);56 var (popupTarget, _) = await TaskUtils.WhenAll(57 popupTargetCompletion.Task,58 page.EvaluateAsync("url => window.open(url)", Server.EmptyPage)59 );60 Assert.AreEqual(context, popupTarget.Context);61 await context.CloseAsync();62 }63 [PlaywrightTest("browsercontext-basic.spec.ts", "should isolate localStorage and cookies")]64 public async Task ShouldIsolateLocalStorageAndCookies()65 {66 // Create two incognito contexts.67 await using var browser = await BrowserType.LaunchAsync();68 var context1 = await browser.NewContextAsync();69 var context2 = await browser.NewContextAsync();70 Assert.IsEmpty(context1.Pages);71 Assert.IsEmpty(context2.Pages);72 // Create a page in first incognito context.73 var page1 = await context1.NewPageAsync();74 await page1.GotoAsync(Server.EmptyPage);75 await page1.EvaluateAsync(@"() => {76 localStorage.setItem('name', 'page1');77 document.cookie = 'name=page1';78 }");79 Assert.That(context1.Pages, Has.Count.EqualTo(1));80 Assert.IsEmpty(context2.Pages);81 // Create a page in second incognito context.82 var page2 = await context2.NewPageAsync();83 await page2.GotoAsync(Server.EmptyPage);84 await page2.EvaluateAsync(@"() => {85 localStorage.setItem('name', 'page2');86 document.cookie = 'name=page2';87 }");88 Assert.That(context1.Pages, Has.Count.EqualTo(1));89 Assert.AreEqual(page1, context1.Pages.FirstOrDefault());90 Assert.That(context2.Pages, Has.Count.EqualTo(1));91 Assert.AreEqual(page2, context2.Pages.FirstOrDefault());92 // Make sure pages don't share localstorage or cookies.93 Assert.AreEqual("page1", await page1.EvaluateAsync<string>("() => localStorage.getItem('name')"));94 Assert.AreEqual("name=page1", await page1.EvaluateAsync<string>("() => document.cookie"));95 Assert.AreEqual("page2", await page2.EvaluateAsync<string>("() => localStorage.getItem('name')"));96 Assert.AreEqual("name=page2", await page2.EvaluateAsync<string>("() => document.cookie"));97 // Cleanup contexts.98 await TaskUtils.WhenAll(context1.CloseAsync(), context2.CloseAsync());99 Assert.IsEmpty(browser.Contexts);100 }101 [PlaywrightTest("browsercontext-basic.spec.ts", "should propagate default viewport to the page")]102 public async Task ShouldPropagateDefaultViewportToThePage()103 {104 await using var context = await Browser.NewContextAsync(new()105 {106 ViewportSize = new()107 {108 Width = 456,109 Height = 789110 }111 });112 var page = await context.NewPageAsync();113 await TestUtils.VerifyViewportAsync(page, 456, 789);114 }115 [PlaywrightTest("browsercontext-basic.spec.ts", "should make a copy of default viewport")]116 public async Task ShouldMakeACopyOfDefaultViewport()117 {118 var viewport = new ViewportSize119 {120 Width = 456,121 Height = 789122 };123 await using var context = await Browser.NewContextAsync(new() { ViewportSize = viewport });124 viewport.Width = 567;125 var page = await context.NewPageAsync();126 await TestUtils.VerifyViewportAsync(page, 456, 789);127 }128 [PlaywrightTest("browsercontext-basic.spec.ts", "should respect deviceScaleFactor")]129 public async Task ShouldRespectDeviceScaleFactor()130 {131 await using var context = await Browser.NewContextAsync(new()132 {133 DeviceScaleFactor = 3134 });135 var page = await context.NewPageAsync();136 Assert.AreEqual(3, await page.EvaluateAsync<int>("window.devicePixelRatio"));137 }138 [PlaywrightTest("browsercontext-basic.spec.ts", "should not allow deviceScaleFactor with null viewport")]139 public async Task ShouldNotAllowDeviceScaleFactorWithViewportDisabled()140 {141 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Browser.NewContextAsync(new()142 {143 ViewportSize = ViewportSize.NoViewport,144 DeviceScaleFactor = 3,145 }));146 Assert.AreEqual("\"deviceScaleFactor\" option is not supported with null \"viewport\"", exception.Message);147 }148 [PlaywrightTest("browsercontext-basic.spec.ts", "should not allow isMobile with null viewport")]149 public async Task ShouldNotAllowIsMobileWithViewportDisabled()150 {151 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Browser.NewContextAsync(new()152 {153 ViewportSize = ViewportSize.NoViewport,154 IsMobile = true,155 }));156 Assert.AreEqual("\"isMobile\" option is not supported with null \"viewport\"", exception.Message);157 }158 [PlaywrightTest("browsercontext-basic.spec.ts", "close() should work for empty context")]159 public async Task CloseShouldWorkForEmptyContext()160 {161 var context = await Browser.NewContextAsync();162 await context.CloseAsync();163 }164 [PlaywrightTest("browsercontext-basic.spec.ts", "close() should abort waitForEvent")]165 public async Task CloseShouldAbortWaitForEvent()166 {167 var context = await Browser.NewContextAsync();168 var waitTask = context.WaitForPageAsync();169 await context.CloseAsync();170 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => waitTask);171 Assert.AreEqual("Context closed", exception.Message);172 }173 [PlaywrightTest("browsercontext-basic.spec.ts", "should not report frameless pages on error")]174 public async Task ShouldNotReportFramelessPagesOnError()175 {176 var context = await Browser.NewContextAsync();177 var page = await context.NewPageAsync();178 Server.SetRoute("/empty.html", context =>179 {180 context.Response.ContentType = "text/html";181 return context.Response.WriteAsync($"<a href=\"{Server.EmptyPage}\" target=\"_blank\">Click me</a>");182 });183 IPage popup = null;184 context.Page += (_, e) => popup = e;185 await page.GotoAsync(Server.EmptyPage);186 await page.ClickAsync("'Click me'");187 await context.CloseAsync();188 if (popup != null)189 {190 Assert.True(popup.IsClosed);191 Assert.NotNull(popup.MainFrame);192 }193 }194 [PlaywrightTest("browsercontext-basic.spec.ts", "close() should be callable twice")]195 public async Task CloseShouldBeCallableTwice()196 {197 var context = await Browser.NewContextAsync();198 await TaskUtils.WhenAll(context.CloseAsync(), context.CloseAsync());199 await context.CloseAsync();200 }201 [PlaywrightTest("browsercontext-basic.spec.ts", "should return all of the pages")]202 public async Task ShouldReturnAllOfThePages()203 {204 await using var context = await Browser.NewContextAsync();205 var page = await context.NewPageAsync();206 var second = await context.NewPageAsync();207 Assert.AreEqual(2, context.Pages.Count);208 CollectionAssert.Contains(context.Pages, page);209 CollectionAssert.Contains(context.Pages, second);210 }211 [PlaywrightTest("browsercontext-basic.spec.ts", "BrowserContext.pages()", "should close all belonging pages once closing context")]212 public async Task ShouldCloseAllBelongingPagesOnceClosingContext()213 {214 await using var context = await Browser.NewContextAsync();215 await context.NewPageAsync();216 Assert.That(context.Pages, Has.Count.EqualTo(1));217 await context.CloseAsync();218 Assert.IsEmpty(context.Pages);219 }220 [PlaywrightTest("browsercontext-basic.spec.ts", "should disable javascript")]221 public async Task ShouldDisableJavascript()222 {223 await using (var context = await Browser.NewContextAsync(new() { JavaScriptEnabled = false }))224 {225 var page = await context.NewPageAsync();226 await page.GotoAsync("data:text/html, <script>var something = 'forbidden'</script>");227 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.EvaluateAsync("something"));228 StringAssert.Contains(229 TestConstants.IsWebKit ? "Can't find variable: something" : "something is not defined",230 exception.Message);231 }232 await using (var context = await Browser.NewContextAsync())233 {234 var page = await context.NewPageAsync();235 await page.GotoAsync("data:text/html, <script>var something = 'forbidden'</script>");236 Assert.AreEqual("forbidden", await page.EvaluateAsync<string>("something"));237 }238 }239 [PlaywrightTest("browsercontext-basic.spec.ts", "should be able to navigate after disabling javascript")]240 public async Task ShouldBeAbleToNavigateAfterDisablingJavascript()241 {242 await using var context = await Browser.NewContextAsync(new() { JavaScriptEnabled = false });243 var page = await context.NewPageAsync();244 await page.GotoAsync(Server.EmptyPage);245 }246 [PlaywrightTest("browsercontext-basic.spec.ts", "should work with offline option")]247 public async Task ShouldWorkWithOfflineOption()248 {249 await using var context = await Browser.NewContextAsync(new() { Offline = true });250 var page = await context.NewPageAsync();251 await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.GotoAsync(Server.EmptyPage));252 await context.SetOfflineAsync(false);253 var response = await page.GotoAsync(Server.EmptyPage);254 Assert.AreEqual((int)HttpStatusCode.OK, response.Status);255 }256 [PlaywrightTest("browsercontext-basic.spec.ts", "should emulate navigator.onLine")]257 [Skip(SkipAttribute.Targets.Firefox)]258 public async Task ShouldEmulateNavigatorOnLine()259 {260 await using var context = await Browser.NewContextAsync();261 var page = await context.NewPageAsync();262 Assert.True(await page.EvaluateAsync<bool>("() => window.navigator.onLine"));263 await context.SetOfflineAsync(true);264 Assert.False(await page.EvaluateAsync<bool>("() => window.navigator.onLine"));265 await context.SetOfflineAsync(false);266 Assert.True(await page.EvaluateAsync<bool>("() => window.navigator.onLine"));267 }268 }269}...

Full Screen

Full Screen

DefaultBrowserContext1Tests.cs

Source:DefaultBrowserContext1Tests.cs Github

copy

Full Screen

...35 public async Task ContextCookiesShouldWork()36 {37 var (tmp, context, page) = await LaunchPersistentAsync();38 await page.GotoAsync(Server.EmptyPage);39 string documentCookie = await page.EvaluateAsync<string>(@"() => {40 document.cookie = 'username=John Doe';41 return document.cookie;42 }");43 Assert.AreEqual("username=John Doe", documentCookie);44 var cookie = (await page.Context.CookiesAsync()).Single();45 Assert.AreEqual("username", cookie.Name);46 Assert.AreEqual("John Doe", cookie.Value);47 Assert.AreEqual("localhost", cookie.Domain);48 Assert.AreEqual("/", cookie.Path);49 Assert.AreEqual(-1, cookie.Expires);50 Assert.IsFalse(cookie.HttpOnly);51 Assert.IsFalse(cookie.Secure);52 Assert.AreEqual(TestConstants.IsChromium ? SameSiteAttribute.Lax : SameSiteAttribute.None, cookie.SameSite);53 await context.DisposeAsync();54 tmp.Dispose();55 }56 [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "context.addCookies() should work")]57 public async Task ContextAddCookiesShouldWork()58 {59 var (tmp, context, page) = await LaunchPersistentAsync();60 await page.GotoAsync(Server.EmptyPage);61 await context.AddCookiesAsync(new[]62 {63 new Cookie64 {65 Url = Server.EmptyPage,66 Name = "username",67 Value = "John Doe",68 }69 });70 Assert.AreEqual("username=John Doe", await page.EvaluateAsync<string>(@"() => document.cookie"));71 var cookie = (await page.Context.CookiesAsync()).Single();72 Assert.AreEqual("username", cookie.Name);73 Assert.AreEqual("John Doe", cookie.Value);74 Assert.AreEqual("localhost", cookie.Domain);75 Assert.AreEqual("/", cookie.Path);76 Assert.AreEqual(-1, cookie.Expires);77 Assert.IsFalse(cookie.HttpOnly);78 Assert.IsFalse(cookie.Secure);79 Assert.AreEqual(TestConstants.IsChromium ? SameSiteAttribute.Lax : SameSiteAttribute.None, cookie.SameSite);80 await context.DisposeAsync();81 tmp.Dispose();82 }83 [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "context.clearCookies() should work")]84 public async Task ContextClearCookiesShouldWork()85 {86 var (tmp, context, page) = await LaunchPersistentAsync();87 await page.GotoAsync(Server.EmptyPage);88 await context.AddCookiesAsync(new[]89 {90 new Cookie91 {92 Url = Server.EmptyPage,93 Name = "cookie1",94 Value = "1",95 },96 new Cookie97 {98 Url = Server.EmptyPage,99 Name = "cookie2",100 Value = "2",101 },102 });103 Assert.AreEqual("cookie1=1; cookie2=2", await page.EvaluateAsync<string>(@"() => document.cookie"));104 await context.ClearCookiesAsync();105 await page.ReloadAsync();106 Assert.That(await page.Context.CookiesAsync(), Is.Empty);107 Assert.That(await page.EvaluateAsync<string>(@"() => document.cookie"), Is.Empty);108 await context.DisposeAsync();109 tmp.Dispose();110 }111 [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should(not) block third party cookies")]112 public async Task ShouldNotBlockThirdPartyCookies()113 {114 var (tmp, context, page) = await LaunchPersistentAsync();115 await page.GotoAsync(Server.EmptyPage);116 await page.EvaluateAsync(@"src => {117 let fulfill;118 const promise = new Promise(x => fulfill = x);119 const iframe = document.createElement('iframe');120 document.body.appendChild(iframe);121 iframe.onload = fulfill;122 iframe.src = src;123 return promise;124 }", Server.CrossProcessPrefix + "/grid.html");125 await page.FirstChildFrame().EvaluateAsync<string>("document.cookie = 'username=John Doe'");126 await page.WaitForTimeoutAsync(2000);127 bool allowsThirdParty = TestConstants.IsFirefox;128 var cookies = await context.CookiesAsync(new[] { Server.CrossProcessPrefix + "/grid.html" });129 if (allowsThirdParty)130 {131 Assert.That(cookies, Has.Count.EqualTo(1));132 var cookie = cookies.First();133 Assert.AreEqual("127.0.0.1", cookie.Domain);134 Assert.AreEqual(cookie.Expires, -1);135 Assert.IsFalse(cookie.HttpOnly);136 Assert.AreEqual("username", cookie.Name);137 Assert.AreEqual("/", cookie.Path);138 Assert.AreEqual(TestConstants.IsChromium ? SameSiteAttribute.Lax : SameSiteAttribute.None, cookie.SameSite);139 Assert.IsFalse(cookie.Secure);140 Assert.AreEqual("John Doe", cookie.Value);141 }142 else143 {144 Assert.That(cookies, Is.Empty);145 }146 await context.DisposeAsync();147 tmp.Dispose();148 }149 [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support viewport option")]150 public async Task ShouldSupportViewportOption()151 {152 var (tmp, context, page) = await LaunchPersistentAsync(new()153 {154 ViewportSize = new()155 {156 Width = 456,157 Height = 789158 }159 });160 await TestUtils.VerifyViewportAsync(page, 456, 789);161 page = await context.NewPageAsync();162 await TestUtils.VerifyViewportAsync(page, 456, 789);163 await context.DisposeAsync();164 tmp.Dispose();165 }166 [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support deviceScaleFactor option")]167 public async Task ShouldSupportDeviceScaleFactorOption()168 {169 var (tmp, context, page) = await LaunchPersistentAsync(new()170 {171 DeviceScaleFactor = 3172 });173 Assert.AreEqual(3, await page.EvaluateAsync<int>("window.devicePixelRatio"));174 await context.DisposeAsync();175 tmp.Dispose();176 }177 [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support userAgent option")]178 public async Task ShouldSupportUserAgentOption()179 {180 var (tmp, context, page) = await LaunchPersistentAsync(new()181 {182 UserAgent = "foobar"183 });184 string userAgent = string.Empty;185 await TaskUtils.WhenAll(186 Server.WaitForRequest("/empty.html", r => userAgent = r.Headers["user-agent"]),187 page.GotoAsync(Server.EmptyPage));188 Assert.AreEqual("foobar", userAgent);189 await context.DisposeAsync();190 tmp.Dispose();191 }192 [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support bypassCSP option")]193 public async Task ShouldSupportBypassCSPOption()194 {195 var (tmp, context, page) = await LaunchPersistentAsync(new()196 {197 BypassCSP = true198 });199 await page.GotoAsync(Server.Prefix + "/csp.html");200 await page.AddScriptTagAsync(new() { Content = "window.__injected = 42;" });201 Assert.AreEqual(42, await page.EvaluateAsync<int>("window.__injected"));202 await context.DisposeAsync();203 tmp.Dispose();204 }205 [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support javascriptEnabled option")]206 public async Task ShouldSupportJavascriptEnabledOption()207 {208 var (tmp, context, page) = await LaunchPersistentAsync(new()209 {210 JavaScriptEnabled = false211 });212 await page.GotoAsync("data:text/html, <script>var something = \"forbidden\"</script>");213 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.EvaluateAsync("something"));214 if (TestConstants.IsWebKit)215 {216 StringAssert.Contains("Can't find variable: something", exception.Message);217 }218 else219 {220 StringAssert.Contains("something is not defined", exception.Message);221 }222 await context.DisposeAsync();223 tmp.Dispose();224 }225 [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support httpCredentials option")]226 public async Task ShouldSupportHttpCredentialsOption()227 {...

Full Screen

Full Screen

PageAutoWaitingBasicTests.cs

Source:PageAutoWaitingBasicTests.cs Github

copy

Full Screen

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

Full Screen

Full Screen

PageWaitForUrlTests.cs

Source:PageWaitForUrlTests.cs Github

copy

Full Screen

...35 [PlaywrightTest("page-wait-for-url.spec.ts", "should work")]36 public async Task ShouldWork()37 {38 await Page.GotoAsync(Server.EmptyPage);39 await Page.EvaluateAsync("url => window.location.href = url", Server.Prefix + "/grid.html");40 await Page.WaitForURLAsync("**/grid.html");41 }42 [PlaywrightTest("page-wait-for-url.spec.ts", "should respect timeout")]43 public async Task ShouldRespectTimeout()44 {45 var task = Page.WaitForURLAsync("**/frame.html", new() { Timeout = 2500 });46 await Page.GotoAsync(Server.EmptyPage);47 var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(() => task);48 StringAssert.Contains("Timeout 2500ms exceeded.", exception.Message);49 }50 [PlaywrightTest("page-wait-for-url.spec.ts", "should work with both domcontentloaded and load")]51 public async Task UrlShouldWorkWithBothDomcontentloadedAndLoad()52 {53 var responseTask = new TaskCompletionSource<bool>();54 Server.SetRoute("/one-style.css", async (ctx) =>55 {56 if (await responseTask.Task)57 {58 await ctx.Response.WriteAsync("Some css");59 }60 });61 var waitForRequestTask = Server.WaitForRequest("/one-style.css");62 var navigationTask = Page.GotoAsync(Server.Prefix + "/one-style.html");63 var domContentLoadedTask = Page.WaitForURLAsync("**/one-style.html", new() { WaitUntil = WaitUntilState.DOMContentLoaded });64 var bothFiredTask = Task.WhenAll(65 Page.WaitForURLAsync("**/one-style.html", new() { WaitUntil = WaitUntilState.Load }),66 domContentLoadedTask);67 await waitForRequestTask;68 await domContentLoadedTask;69 Assert.False(bothFiredTask.IsCompleted);70 responseTask.TrySetResult(true);71 await bothFiredTask;72 await navigationTask;73 }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);115 }116 [PlaywrightTest("page-wait-for-url.spec.ts", "should work with url match for same document navigations")]117 public async Task ShouldWorkWithUrlMatchForSameDocumentNavigations()118 {119 await Page.GotoAsync(Server.EmptyPage);120 var waitPromise = Page.WaitForURLAsync(new Regex("third\\.html"));121 Assert.False(waitPromise.IsCompleted);122 await Page.EvaluateAsync(@"() => {123 history.pushState({}, '', '/first.html');124 }");125 Assert.False(waitPromise.IsCompleted);126 await Page.EvaluateAsync(@"() => {127 history.pushState({}, '', '/second.html');128 }");129 Assert.False(waitPromise.IsCompleted);130 await Page.EvaluateAsync(@"() => {131 history.pushState({}, '', '/third.html');132 }");133 await waitPromise;134 }135 [PlaywrightTest("page-wait-for-url.spec.ts", "should work on frame")]136 public async Task ShouldWorkOnFrame()137 {138 await Page.GotoAsync(Server.Prefix + "/frames/one-frame.html");139 var frame = Page.Frames.ElementAt(1);140 await TaskUtils.WhenAll(141 frame.WaitForURLAsync("**/grid.html"),142 frame.EvaluateAsync("url => window.location.href = url", Server.Prefix + "/grid.html"));143 ;144 }145 }146}...

Full Screen

Full Screen

PageWaitForLoadStateTests.cs

Source:PageWaitForLoadStateTests.cs Github

copy

Full Screen

...91 [Skip(SkipAttribute.Targets.Firefox, SkipAttribute.Targets.Webkit)]92 public async Task ShouldWorkWithPagesThatHaveLoadedBeforeBeingConnectedTo()93 {94 await Page.GotoAsync(Server.EmptyPage);95 await Page.EvaluateAsync(@"async () => {96 const child = window.open(document.location.href);97 while (child.document.readyState !== 'complete' || child.document.location.href === 'about:blank')98 await new Promise(f => setTimeout(f, 100));99 }");100 var pages = Context.Pages;101 Assert.AreEqual(2, pages.Count);102 // order is not guaranteed103 var mainPage = pages.FirstOrDefault(p => ReferenceEquals(Page, p));104 var connectedPage = pages.Single(p => !ReferenceEquals(Page, p));105 Assert.NotNull(mainPage);106 Assert.AreEqual(Server.EmptyPage, mainPage.Url);107 Assert.AreEqual(Server.EmptyPage, connectedPage.Url);108 await connectedPage.WaitForLoadStateAsync();109 Assert.AreEqual(Server.EmptyPage, connectedPage.Url);110 }111 [PlaywrightTest("page-wait-for-load-state.spec.ts", "should work for frame")]112 public async Task ShouldWorkForFrame()113 {114 await Page.GotoAsync(Server.Prefix + "/frames/one-frame.html");115 var frame = Page.Frames.ElementAt(1);116 TaskCompletionSource<bool> requestTask = new TaskCompletionSource<bool>();117 TaskCompletionSource<bool> routeReachedTask = new TaskCompletionSource<bool>();118 await Page.RouteAsync(Server.Prefix + "/one-style.css", async (route) =>119 {120 routeReachedTask.TrySetResult(true);121 await requestTask.Task;122 await route.ContinueAsync();123 });124 await frame.GotoAsync(Server.Prefix + "/one-style.html", new() { WaitUntil = WaitUntilState.DOMContentLoaded });125 await routeReachedTask.Task;126 var loadTask = frame.WaitForLoadStateAsync();127 await Page.EvaluateAsync("1");128 Assert.False(loadTask.IsCompleted);129 requestTask.TrySetResult(true);130 await loadTask;131 }132 }133}...

Full Screen

Full Screen

IgnoreHttpsErrorsTests.cs

Source:IgnoreHttpsErrorsTests.cs Github

copy

Full Screen

...68 await using var context = await Browser.NewContextAsync(new() { IgnoreHTTPSErrors = true });69 var page = await context.NewPageAsync();70 await page.GotoAsync(HttpsServer.Prefix + "/mixedcontent.html", new() { WaitUntil = WaitUntilState.DOMContentLoaded });71 Assert.AreEqual(2, page.Frames.Count);72 Assert.AreEqual(3, await page.MainFrame.EvaluateAsync<int>("1 + 2"));73 Assert.AreEqual(5, await page.FirstChildFrame().EvaluateAsync<int>("2 + 3"));74 }75 [PlaywrightTest("ignorehttpserrors.spec.ts", "should work with WebSocket")]76 public async Task ShouldWorkWithWebSocket()77 {78 HttpsServer.SendOnWebSocketConnection("incoming");79 await using var context = await Browser.NewContextAsync(new() { IgnoreHTTPSErrors = true });80 var page = await context.NewPageAsync();81 string value = await page.EvaluateAsync<string>(@"endpoint => {82 let cb;83 const result = new Promise(f => cb = f);84 const ws = new WebSocket(endpoint);85 ws.addEventListener('message', data => { ws.close(); cb(data.data); });86 ws.addEventListener('error', error => cb('Error'));87 return result;88 }", HttpsServer.Prefix.Replace("https", "wss") + "/ws");89 Assert.AreEqual("incoming", value);90 }91 [PlaywrightTest("ignorehttpserrors.spec.ts", "should fail with WebSocket if not ignored")]92 public async Task ShouldFailWithWebSocketIfNotIgnored()93 {94 await using var context = await Browser.NewContextAsync();95 var page = await context.NewPageAsync();96 string value = await page.EvaluateAsync<string>(@"endpoint => {97 let cb;98 const result = new Promise(f => cb = f);99 const ws = new WebSocket(endpoint);100 ws.addEventListener('message', data => { ws.close(); cb(data.data); });101 ws.addEventListener('error', error => cb('Error'));102 return result;103 }", HttpsServer.Prefix.Replace("https", "wss") + "/ws");104 Assert.AreEqual("Error", value);105 }106 }107}...

Full Screen

Full Screen

EvaluateAsync

Using AI Code Generation

copy

Full Screen

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 BrowserTypeLaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 var search = await page.QuerySelectorAsync("input[name=q]");14 await search.TypeAsync("Playwright");15 await page.Keyboard.PressAsync("Enter");16 var result = await page.EvaluateAsync<string>("() => document.querySelector('a[href*=\"playwright.dev\"]')?.innerText");17 Console.WriteLine(result);18 }19 }20}21using Microsoft.Playwright;22using System;23using System.Threading.Tasks;24{25 {26 static async Task Main(string[] args)27 {28 using var playwright = await Playwright.CreateAsync();29 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions30 {31 });32 var page = await browser.NewPageAsync();33 var search = await page.QuerySelectorAsync("input[name=q]");34 await search.TypeAsync("Playwright");35 await page.Keyboard.PressAsync("Enter");36 var result = await page.EvaluateAsync<string>("() => document.querySelector('a[href*=\"playwright.dev\"]')?.innerText");37 Console.WriteLine(result);38 }39 }40}41using Microsoft.Playwright;42using System;43using System.Threading.Tasks;44{45 {46 static async Task Main(string[] args)47 {48 using var playwright = await Playwright.CreateAsync();49 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions50 {51 });52 var page = await browser.NewPageAsync();53 await page.GotoAsync("https

Full Screen

Full Screen

EvaluateAsync

Using AI Code Generation

copy

Full Screen

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("input[aria-label='Search']", "Hello World!");14 await page.PressAsync("input[aria-label='Search']", "Enter");15 var result = await page.EvaluateAsync<string>("() => document.querySelector('.g').innerText");16 Console.WriteLine(result);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("input[aria-label='Search']", "Hello World!");33 await page.PressAsync("input[aria-label='Search']", "Enter");34 var result = await page.EvaluateHandleAsync("() => document.querySelector('.g')");35 Console.WriteLine(await result.GetAttributeAsync("innerText"));36 }37 }38}39using System;40using System.Threading.Tasks;41using Microsoft.Playwright;42{43 {44 static async Task Main(string[] args)45 {46 using var playwright = await Playwright.CreateAsync();47 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions48 {49 });50 var page = await browser.NewPageAsync();51 await page.TypeAsync("input[aria-label='Search']", "Hello World!");52 await page.PressAsync("input[aria-label='

Full Screen

Full Screen

EvaluateAsync

Using AI Code Generation

copy

Full Screen

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 var result = await page.EvaluateAsync<string>("() => document.title");12 Console.WriteLine(result);13 await browser.CloseAsync();14 }15 }16}17using Microsoft.Playwright;18using System;19using System.Threading.Tasks;20{21 {22 static async Task Main(string[] args)23 {24 using var playwright = await Playwright.CreateAsync();25 await using var browser = await playwright.Chromium.LaunchAsync();26 var page = await browser.NewPageAsync();27 var result = await page.EvaluateAsync<string>("() => document.title");28 Console.WriteLine(result);29 await browser.CloseAsync();30 }31 }32}

Full Screen

Full Screen

EvaluateAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4using Microsoft.Playwright.Core;5{6 {7 static async Task Main(string[] args)8 {9 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 var element = await page.QuerySelectorAsync("input[title='Search']");15 var value = await element.EvaluateAsync<string>("e => e.value");16 Console.WriteLine(value);17 }18 }19}20using System;21using System.Threading.Tasks;22using Microsoft.Playwright;23using Microsoft.Playwright.Core;24{25 {26 static async Task Main(string[] args)27 {28 using var playwright = await Playwright.CreateAsync();29 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions30 {31 });32 var page = await browser.NewPageAsync();33 var value = await page.EvaluateAsync<string>("() => document.title");34 Console.WriteLine(value);35 }36 }37}38using System;39using System.Threading.Tasks;40using Microsoft.Playwright;41using Microsoft.Playwright.Core;42{43 {44 static async Task Main(string[] args)45 {46 using var playwright = await Playwright.CreateAsync();47 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions48 {49 });50 var page = await browser.NewPageAsync();

Full Screen

Full Screen

EvaluateAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4{5 {6 static async Task Main(string[] args)7 {8 await using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 await page.EvaluateAsync(@"() => {14 const input = document.querySelector('input[title=""Search""]');15 input.value = 'Hello world!';16 input.dispatchEvent(new Event('input', { bubbles: true }));17 return input.value;18 }");19 }20 }21}

Full Screen

Full Screen

EvaluateAsync

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using System.Threading.Tasks;3{4 {5 static async Task Main(string[] args)6 {7 using var playwright = await Playwright.CreateAsync();8 var browser = await playwright.Chromium.LaunchAsync();9 var page = await browser.NewPageAsync();10 await page.ClickAsync("text=Docs");11 var handle = await page.EvaluateHandleAsync("() => document.querySelector('h1')");12 var value = await handle.EvaluateAsync<string>("node => node.textContent");13 System.Console.WriteLine(value);14 await browser.CloseAsync();15 }16 }17}18using Microsoft.Playwright;19using System.Threading.Tasks;20{21 {22 static async Task Main(string[] args)23 {24 using var playwright = await Playwright.CreateAsync();25 var browser = await playwright.Chromium.LaunchAsync();26 var page = await browser.NewPageAsync();27 await page.ClickAsync("text=Docs");28 var handle = await page.QuerySelectorAsync("h1");29 var value = await handle.EvaluateAsync<string>("node => node.textContent");30 System.Console.WriteLine(value);31 await browser.CloseAsync();32 }33 }34}35using Microsoft.Playwright;36using System.Threading.Tasks;37{38 {39 static async Task Main(string[] args)40 {41 using var playwright = await Playwright.CreateAsync();42 var browser = await playwright.Chromium.LaunchAsync();43 var page = await browser.NewPageAsync();44 await page.ClickAsync("text=Docs");45 var value = await page.EvaluateAsync<string>("() => document.querySelector('h1').textContent");46 System.Console.WriteLine(value);47 await browser.CloseAsync();48 }

Full Screen

Full Screen

EvaluateAsync

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using Microsoft.Playwright.Core;3using System;4using System.Threading.Tasks;5{6 {7 static async Task Main(string[] args)8 {9 using var playwright = await Playwright.CreateAsync();10 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions11 {12 });13 var context = await browser.NewContextAsync();14 var page = await context.NewPageAsync();15 var result = await page.EvaluateAsync<int>("() => 1 + 2");16 Console.WriteLine(result);17 await browser.CloseAsync();18 }19 }20}21using Microsoft.Playwright;22using Microsoft.Playwright.Core;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 BrowserTypeLaunchOptions31 {32 });33 var context = await browser.NewContextAsync();34 var page = await context.NewPageAsync();35 var title = await page.EvaluateAsync<string>("() => document.title");36 Console.WriteLine(title);37 await browser.CloseAsync();38 }39 }40}41using Microsoft.Playwright;42using Microsoft.Playwright.Core;

Full Screen

Full Screen

EvaluateAsync

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using System.Threading.Tasks;3{4 {5 public static async Task Main()6 {7 using var playwright = await Playwright.CreateAsync();8 var browser = await playwright.Chromium.LaunchAsync(headless: false);9 var page = await browser.NewPageAsync();10 await page.TypeAsync("input[aria-label='Search']", "Playwright");11 await page.ClickAsync("input[value='Google Search']");12 await page.WaitForNavigationAsync();13 var result = await page.EvaluateAsync<int>("() => document.querySelectorAll('a').length");14 await page.ScreenshotAsync("result.png");15 await browser.CloseAsync();16 }17 }18}

Full Screen

Full Screen

EvaluateAsync

Using AI Code Generation

copy

Full Screen

1var frame = await context.FirstChildFrameAsync();2var result = await frame.EvaluateAsync<string>("() => document.querySelector('h1').innerText");3var result = await page.EvaluateAsync<string>("() => document.querySelector('h1').innerText");4var result = await playwrightPage.EvaluateAsync<string>("() => document.querySelector('h1').innerText");5var result = await playwrightElementHandle.EvaluateAsync<string>("() => document.querySelector('h1').innerText");6var result = await playwrightFrame.EvaluateAsync<string>("() => document.querySelector('h1').innerText");7var result = await playwrightJsHandle.EvaluateAsync<string>("() => document.querySelector('h1').innerText");8 System.Console.WriteLine(value);9 await browser.CloseAsync();10 }11 }12}13using Microsoft.Playwright;14using System.Threading.Tasks;15{16 {17 static async Task Main(string[] args)18 {19 using var playwright = await Playwright.CreateAsync();20 var browser = await playwright.Chromium.LaunchAsync();21 var page = await browser.NewPageAsync();22 await page.ClickAsync("text=Docs");23 var value = await page.EvaluateAsync<string>("() => document.querySelector('h1').textContent");24 System.Console.WriteLine(value);25 await browser.CloseAsync();26 }

Full Screen

Full Screen

EvaluateAsync

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using Microsoft.Playwright.Core;3using System;4using System.Threading.Tasks;5{6 {7 static async Task Main(string[] args)8 {9 using var playwright = await Playwright.CreateAsync();10 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions11 {12 });13 var context = await browser.NewContextAsync();14 var page = await context.NewPageAsync();15 var result = await page.EvaluateAsync<int>("() => 1 + 2");16 Console.WriteLine(result);17 await browser.CloseAsync();18 }19 }20}21using Microsoft.Playwright;22using Microsoft.Playwright.Core;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 BrowserTypeLaunchOptions31 {32 });33 var context = await browser.NewContextAsync();34 var page = await context.NewPageAsync();35 var title = await page.EvaluateAsync<string>("() => document.title");36 Console.WriteLine(title);37 await browser.CloseAsync();38 }39 }40}41using Microsoft.Playwright;42using Microsoft.Playwright.Core;

Full Screen

Full Screen

EvaluateAsync

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using System.Threading.Tasks;3{4 {5 public static async Task Main()6 {7 using var playwright = await Playwright.CreateAsync();8 var browser = await playwright.Chromium.LaunchAsync(headless: false);9 var page = await browser.NewPageAsync();10 await page.TypeAsync("input[aria-label='Search']", "Playwright");11 await page.ClickAsync("input[value='Google Search']");12 await page.WaitForNavigationAsync();13 var result = await page.EvaluateAsync<int>("() => document.querySelectorAll('a').length");14 await page.ScreenshotAsync("result.png");15 await browser.CloseAsync();16 }17 }18}

Full Screen

Full Screen

EvaluateAsync

Using AI Code Generation

copy

Full Screen

1var frame = await context.FirstChildFrameAsync();2var result = await frame.EvaluateAsync<string>("() => document.querySelector('h1').innerText");3var result = await page.EvaluateAsync<string>("() => document.querySelector('h1').innerText");4var result = await playwrightPage.EvaluateAsync<string>("() => document.querySelector('h1').innerText");5var result = await playwrightElementHandle.EvaluateAsync<string>("() => document.querySelector('h1').innerText");6var result = await playwrightFrame.EvaluateAsync<string>("() => document.querySelector('h1').innerText");7var result = await playwrightJsHandle.EvaluateAsync<string>("() => document.querySelector('h1').innerText");8 var browser = await playwright.Chromium.LaunchAsync();9 var page = await browser.NewPageAsync();10 await page.ClickAsync("text=Docs");11 var value = await page.EvaluateAsync<string>("() => document.querySelector('h1').textContent");12 System.Console.WriteLine(value);13 await browser.CloseAsync();14 }

Full Screen

Full Screen

EvaluateAsync

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using Microsoft.Playwright.Core;3using System;4using System.Threading.Tasks;5{6 {7 static async Task Main(string[] args)8 {9 using var playwright = await Playwright.CreateAsync();10 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions11 {12 });13 var context = await browser.NewContextAsync();14 var page = await context.NewPageAsync();15 var result = await page.EvaluateAsync<int>("() => 1 + 2");16 Console.WriteLine(result);17 await browser.CloseAsync();18 }19 }20}21using Microsoft.Playwright;22using Microsoft.Playwright.Core;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 BrowserTypeLaunchOptions31 {32 });33 var context = await browser.NewContextAsync();34 var page = await context.NewPageAsync();35 var title = await page.EvaluateAsync<string>("() => document.title");36 Console.WriteLine(title);37 await browser.CloseAsync();38 }39 }40}41using Microsoft.Playwright;42using Microsoft.Playwright.Core;

Full Screen

Full Screen

EvaluateAsync

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using System.Threading.Tasks;3{4 {5 public static async Task Main()6 {7 using var playwright = await Playwright.CreateAsync();8 var browser = await playwright.Chromium.LaunchAsync(headless: false);9 var page = await browser.NewPageAsync();10 await page.TypeAsync("input[aria-label='Search']", "Playwright");11 await page.ClickAsync("input[value='Google Search']");12 await page.WaitForNavigationAsync();13 var result = await page.EvaluateAsync<int>("() => document.querySelectorAll('a').length");14 await page.ScreenshotAsync("result.png");15 await browser.CloseAsync();16 }17 }18}

Full Screen

Full Screen

EvaluateAsync

Using AI Code Generation

copy

Full Screen

1var frame = await context.FirstChildFrameAsync();2var result = await frame.EvaluateAsync<string>("() => document.querySelector('h1').innerText");3var result = await page.EvaluateAsync<string>("() => document.querySelector('h1').innerText");4var result = await playwrightPage.EvaluateAsync<string>("() => document.querySelector('h1').innerText");5var result = await playwrightElementHandle.EvaluateAsync<string>("() => document.querySelector('h1').innerText");6var result = await playwrightFrame.EvaluateAsync<string>("() => document.querySelector('h1').innerText");7var result = await playwrightJsHandle.EvaluateAsync<string>("() => document.querySelector('h1').innerText");

Full Screen

Full Screen

Playwright tutorial

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.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful