Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.Frame.EvalOnSelectorAsync
Page.cs
Source:Page.cs
...361 // Swallow exception362 }363 }364 public Task<T> EvaluateAsync<T>(string expression, object arg) => MainFrame.EvaluateAsync<T>(expression, arg);365 public Task<JsonElement?> EvalOnSelectorAsync(string selector, string expression, object arg) => MainFrame.EvalOnSelectorAsync(selector, expression, arg);366 public Task<T> EvalOnSelectorAsync<T>(string selector, string expression, object arg = null, PageEvalOnSelectorOptions options = null)367 => MainFrame.EvalOnSelectorAsync<T>(selector, expression, arg, new() { Strict = options?.Strict });368 public ILocator Locator(string selector, PageLocatorOptions options = default)369 => MainFrame.Locator(selector, new() { HasTextString = options?.HasTextString, HasTextRegex = options?.HasTextRegex, Has = options?.Has });370 public Task<IElementHandle> QuerySelectorAsync(string selector, PageQuerySelectorOptions options = null)371 => MainFrame.QuerySelectorAsync(selector, new() { Strict = options?.Strict });372 public Task<T> EvalOnSelectorAsync<T>(string selector, string expression, object arg) => MainFrame.EvalOnSelectorAsync<T>(selector, expression, arg);373 public Task<JsonElement?> EvalOnSelectorAllAsync(string selector, string expression, object arg) => MainFrame.EvalOnSelectorAllAsync(selector, expression, arg);374 public Task<T> EvalOnSelectorAllAsync<T>(string selector, string expression, object arg) => MainFrame.EvalOnSelectorAllAsync<T>(selector, expression, arg);375 public Task FillAsync(string selector, string value, PageFillOptions options = default)376 => MainFrame.FillAsync(selector, value, new() { NoWaitAfter = options?.NoWaitAfter, Timeout = options?.Timeout, Force = options?.Force, Strict = options?.Strict });377 public Task SetInputFilesAsync(string selector, string files, PageSetInputFilesOptions options = default)378 => MainFrame.SetInputFilesAsync(selector, files, Map(options));379 public Task SetInputFilesAsync(string selector, IEnumerable<string> files, PageSetInputFilesOptions options = default)380 => MainFrame.SetInputFilesAsync(selector, files, Map(options));381 public Task SetInputFilesAsync(string selector, FilePayload files, PageSetInputFilesOptions options = default)382 => MainFrame.SetInputFilesAsync(selector, files, Map(options));383 public Task SetInputFilesAsync(string selector, IEnumerable<FilePayload> files, PageSetInputFilesOptions options = default)384 => MainFrame.SetInputFilesAsync(selector, files, Map(options));385 public Task TypeAsync(string selector, string text, PageTypeOptions options = default)386 => MainFrame.TypeAsync(selector, text, new()...
PageRouteTests.cs
Source:PageRouteTests.cs
...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;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();...
Frame.cs
Source:Frame.cs
...417 public async Task<T> EvaluateAsync<T>(string script, object arg = null)418 => ScriptsHelper.ParseEvaluateResult<T>(await _channel.EvaluateExpressionAsync(419 script,420 arg: ScriptsHelper.SerializedArgument(arg)).ConfigureAwait(false));421 public async Task<JsonElement?> EvalOnSelectorAsync(string selector, string script, object arg = null)422 => ScriptsHelper.ParseEvaluateResult<JsonElement?>(await _channel.EvalOnSelectorAsync(423 selector: selector,424 script,425 arg: ScriptsHelper.SerializedArgument(arg),426 strict: null).ConfigureAwait(false));427 public async Task<T> EvalOnSelectorAsync<T>(string selector, string script, object arg = null)428 => ScriptsHelper.ParseEvaluateResult<T>(await _channel.EvalOnSelectorAsync(429 selector: selector,430 script,431 arg: ScriptsHelper.SerializedArgument(arg),432 strict: null).ConfigureAwait(false));433 public async Task<T> EvalOnSelectorAsync<T>(string selector, string expression, object arg = null, FrameEvalOnSelectorOptions options = null)434 => ScriptsHelper.ParseEvaluateResult<T>(await _channel.EvalOnSelectorAsync(435 selector: selector,436 expression,437 arg: ScriptsHelper.SerializedArgument(arg),438 strict: options?.Strict).ConfigureAwait(false));439 public async Task<JsonElement?> EvalOnSelectorAllAsync(string selector, string script, object arg = null)440 => ScriptsHelper.ParseEvaluateResult<JsonElement?>(await _channel.EvalOnSelectorAllAsync(441 selector: selector,442 script,443 arg: ScriptsHelper.SerializedArgument(arg)).ConfigureAwait(false));444 public async Task<T> EvalOnSelectorAllAsync<T>(string selector, string script, object arg = null)445 => ScriptsHelper.ParseEvaluateResult<T>(await _channel.EvalOnSelectorAllAsync(446 selector: selector,447 script,448 arg: ScriptsHelper.SerializedArgument(arg)).ConfigureAwait(false));...
FrameChannel.cs
Source:FrameChannel.cs
...121 ["expression"] = script,122 ["arg"] = arg,123 });124 }125 internal Task<JsonElement?> EvalOnSelectorAsync(string selector, string script, object arg, bool? strict)126 => Connection.SendMessageToServerAsync<JsonElement?>(127 Guid,128 "evalOnSelector",129 new Dictionary<string, object>130 {131 ["selector"] = selector,132 ["expression"] = script,133 ["arg"] = arg,134 ["strict"] = strict,135 });136 internal Task<JsonElement?> EvalOnSelectorAllAsync(string selector, string script, object arg)137 => Connection.SendMessageToServerAsync<JsonElement?>(138 Guid,139 "evalOnSelectorAll",...
ElementHandleChannel.cs
Source:ElementHandleChannel.cs
...110 }).ToArray();111 }112 return (await Connection.SendMessageToServerAsync(Guid, "screenshot", args).ConfigureAwait(false))?.GetProperty("binary").GetBytesFromBase64();113 }114 internal Task<JsonElement?> EvalOnSelectorAsync(string selector, string script, object arg)115 => Connection.SendMessageToServerAsync<JsonElement?>(116 Guid,117 "evalOnSelector",118 new Dictionary<string, object>119 {120 ["selector"] = selector,121 ["expression"] = script,122 ["arg"] = arg,123 });124 internal Task<JsonElement?> EvalOnSelectorAllAsync(string selector, string script, object arg)125 => Connection.SendMessageToServerAsync<JsonElement?>(126 Guid,127 "evalOnSelectorAll",128 new Dictionary<string, object>...
Locator.cs
Source:Locator.cs
...114 => _frame.EvalOnSelectorAllAsync<T>(_selector, expression, arg);115 public Task<JsonElement?> EvaluateAsync(string expression, object arg = null, LocatorEvaluateOptions options = null)116 => EvaluateAsync<JsonElement?>(expression, arg, options);117 public Task<T> EvaluateAsync<T>(string expression, object arg = null, LocatorEvaluateOptions options = null)118 => _frame.EvalOnSelectorAsync<T>(_selector, expression, arg, ConvertOptions<FrameEvalOnSelectorOptions>(options));119 public async Task<IJSHandle> EvaluateHandleAsync(string expression, object arg = null, LocatorEvaluateHandleOptions options = null)120 => await WithElementAsync(async (e, _) => await e.EvaluateHandleAsync(expression, arg).ConfigureAwait(false), options).ConfigureAwait(false);121 public async Task FillAsync(string value, LocatorFillOptions options = null)122 => await _frame.FillAsync(_selector, value, ConvertOptions<FrameFillOptions>(options)).ConfigureAwait(false);123 public Task FocusAsync(LocatorFocusOptions options = null)124 => _frame.FocusAsync(_selector, ConvertOptions<FrameFocusOptions>(options));125 IFrameLocator ILocator.FrameLocator(string selector) =>126 new FrameLocator(_frame, $"{_selector} >> {selector}");127 public Task<string> GetAttributeAsync(string name, LocatorGetAttributeOptions options = null)128 => _frame.GetAttributeAsync(_selector, name, ConvertOptions<FrameGetAttributeOptions>(options));129 public Task HoverAsync(LocatorHoverOptions options = null)130 => _frame.HoverAsync(_selector, ConvertOptions<FrameHoverOptions>(options));131 public Task<string> InnerHTMLAsync(LocatorInnerHTMLOptions options = null)132 => _frame.InnerHTMLAsync(_selector, ConvertOptions<FrameInnerHTMLOptions>(options));...
ElementHandle.cs
Source:ElementHandle.cs
...152 public async Task<IElementHandle> QuerySelectorAsync(string selector)153 => (await _channel.QuerySelectorAsync(selector).ConfigureAwait(false))?.Object;154 public async Task<IReadOnlyList<IElementHandle>> QuerySelectorAllAsync(string selector)155 => (await _channel.QuerySelectorAllAsync(selector).ConfigureAwait(false)).Select(e => ((ElementHandleChannel)e).Object).ToList().AsReadOnly();156 public async Task<JsonElement?> EvalOnSelectorAsync(string selector, string expression, object arg = null)157 => ScriptsHelper.ParseEvaluateResult<JsonElement?>(await _channel.EvalOnSelectorAsync(158 selector: selector,159 script: expression,160 arg: ScriptsHelper.SerializedArgument(arg)).ConfigureAwait(false));161 public async Task<T> EvalOnSelectorAsync<T>(string selector, string expression, object arg = null)162 => ScriptsHelper.ParseEvaluateResult<T>(await _channel.EvalOnSelectorAsync(163 selector: selector,164 script: expression,165 arg: ScriptsHelper.SerializedArgument(arg)).ConfigureAwait(false));166 public async Task<T> EvalOnSelectorAllAsync<T>(string selector, string expression, object arg = null)167 => ScriptsHelper.ParseEvaluateResult<T>(await _channel.EvalOnSelectorAllAsync(168 selector: selector,169 script: expression,170 arg: ScriptsHelper.SerializedArgument(arg)).ConfigureAwait(false));171 public Task FocusAsync() => _channel.FocusAsync();172 public Task DispatchEventAsync(string type, object eventInit = null)173 => _channel.DispatchEventAsync(174 type,175 eventInit = ScriptsHelper.SerializedArgument(eventInit));176 public Task<string> GetAttributeAsync(string name) => _channel.GetAttributeAsync(name);...
FrameGoToTests.cs
Source:FrameGoToTests.cs
...51 Server.SetRoute("/empty.html", _ => Task.Delay(10000));52 var waitForRequestTask = Server.WaitForRequest("/empty.html");53 var navigationTask = Page.FirstChildFrame().GotoAsync(Server.EmptyPage);54 await waitForRequestTask;55 await Page.EvalOnSelectorAsync("iframe", "frame => frame.remove()");56 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => navigationTask);57 StringAssert.Contains("frame was detached", exception.Message);58 }59 [PlaywrightTest("frame-goto.spec.ts", "should continue after client redirect")]60 public async Task ShouldContinueAfterClientRedirect()61 {62 Server.SetRoute("/frames/script.js", _ => Task.Delay(10000));63 string url = Server.Prefix + "/frames/child-redirect.html";64 var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(() => Page.GotoAsync(url, new() { WaitUntil = WaitUntilState.NetworkIdle, Timeout = 5000 }));65 StringAssert.Contains("Timeout 5000ms", exception.Message);66 StringAssert.Contains($"navigating to \"{url}\", waiting until \"networkidle\"", exception.Message);67 }68 [PlaywrightTest("frame-goto.spec.ts", "should return matching responses")]69 public async Task ShouldReturnMatchingResponses()...
EvalOnSelectorAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Webkit.LaunchAsync();10 var page = await browser.NewPageAsync();11 var result = await page.EvalOnSelectorAsync<int>("button", "e => e.value");12 Console.WriteLine(result);13 }14 }15}
EvalOnSelectorAsync
Using AI Code Generation
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 BrowserTypeLaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 var searchBox = await page.QuerySelectorAsync("input[name=q]");14 await searchBox.TypeAsync("Playwright");15 var searchButton = await page.QuerySelectorAsync("input[name=btnK]");16 await searchButton.ClickAsync();17 await page.WaitForSelectorAsync("text=Playwright: Node.js library to automate Chromium, Firefox and WebKit with a single API");18 await page.EvalOnSelectorAsync("text=Playwright: Node.js library to automate Chromium, Firefox and WebKit with a single API", @"(element) => {19 element.scrollIntoView();20 element.click();21 }");22 }23 }24}25using System;26using System.Threading.Tasks;27using Microsoft.Playwright;28{29 {30 static async Task Main(string[] args)31 {32 await using var playwright = await Playwright.CreateAsync();33 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions34 {35 });36 var page = await browser.NewPageAsync();37 var searchBox = await page.QuerySelectorAsync("input[name=q]");38 await searchBox.TypeAsync("Playwright");39 var searchButton = await page.QuerySelectorAsync("input[name=btnK]");40 await searchButton.ClickAsync();41 await page.WaitForSelectorAsync("text=Playwright: Node.js library to automate Chromium, Firefox and WebKit with a single API");42 var allElements = await page.EvalOnSelectorAllAsync("text=Playwright: Node.js library to automate Chromium, Firefox and WebKit with a single API", @"(element) => {43 element.scrollIntoView();44 element.click();
EvalOnSelectorAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync(new()10 {11 });12 var page = await browser.NewPageAsync();13 var frame = page.MainFrame.ChildFrames[0];14 var elementHandle = await frame.EvalOnSelectorAsync<ElementHandle>("selector", "code to evaluate");15 }16 }17}18using System;19using System.Threading.Tasks;20using Microsoft.Playwright;21{22 {23 static async Task Main(string[] args)24 {25 using var playwright = await Playwright.CreateAsync();26 await using var browser = await playwright.Chromium.LaunchAsync(new()27 {28 });29 var page = await browser.NewPageAsync();30 var frame = page.MainFrame.ChildFrames[0];31 var elementHandle = await frame.WaitForSelectorAsync("selector");32 }33 }34}35using System;36using System.Threading.Tasks;37using Microsoft.Playwright;38{39 {40 static async Task Main(string[] args)41 {42 using var playwright = await Playwright.CreateAsync();43 await using var browser = await playwright.Chromium.LaunchAsync(new()44 {45 });46 var page = await browser.NewPageAsync();47 var frame = page.MainFrame.ChildFrames[0];48 var elementHandle = await frame.WaitForSelectorAsync("selector", new()49 {50 });51 }52 }53}54using System;55using System.Threading.Tasks;
EvalOnSelectorAsync
Using AI Code Generation
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 BrowserTypeLaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 var result = await page.EvalOnSelectorAsync<string>("input[name='q']", "element => element.value");14 }15 }16}17using System;18using System.Threading.Tasks;19using Microsoft.Playwright;20{21 {22 static async Task Main(string[] args)23 {24 await using var playwright = await Playwright.CreateAsync();25 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions26 {27 });28 var page = await browser.NewPageAsync();29 var result = await page.EvalOnSelectorAllAsync<string>("input[name='q']", "element => element.value");30 }31 }32}33using System;34using System.Threading.Tasks;35using Microsoft.Playwright;36{37 {38 static async Task Main(string[] args)39 {40 await using var playwright = await Playwright.CreateAsync();41 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions42 {43 });44 var page = await browser.NewPageAsync();45 var result = await page.QuerySelectorAsync("input[name='q']");46 await result.FillAsync("test");47 }48 }49}
EvalOnSelectorAsync
Using AI Code Generation
1var playwright = await Microsoft.Playwright.Playwright.CreateAsync();2var browser = await playwright.Chromium.LaunchAsync(new Microsoft.Playwright.LaunchOptions3{4});5var context = await browser.NewContextAsync();6var page = await context.NewPageAsync();7var result = await page.EvalOnSelectorAsync("input[name='q']", "element => element.value");8await browser.CloseAsync();9var playwright = await Microsoft.Playwright.Playwright.CreateAsync();10var browser = await playwright.Chromium.LaunchAsync(new Microsoft.Playwright.LaunchOptions11{12});13var context = await browser.NewContextAsync();14var page = await context.NewPageAsync();15var result = await page.EvalOnSelectorAllAsync("input[name='q']", "elements => elements.length");16await browser.CloseAsync();17var playwright = await Microsoft.Playwright.Playwright.CreateAsync();18var browser = await playwright.Chromium.LaunchAsync(new Microsoft.Playwright.LaunchOptions19{20});21var context = await browser.NewContextAsync();22var page = await context.NewPageAsync();
EvalOnSelectorAsync
Using AI Code Generation
1var page = await browser.NewPageAsync();2var frame = await page.MainFrameAsync();3var result = await frame.EvalOnSelectorAsync("input[name=q]", "e => e.value");4Console.WriteLine(result);5var page = await browser.NewPageAsync();6var frame = await page.MainFrameAsync();7var result = await frame.EvalOnSelectorAllAsync("input", "e => e.length");8Console.WriteLine(result);9var page = await browser.NewPageAsync();10var frame = await page.MainFrameAsync();11var result = await frame.EvaluateAsync("() => 1 + 2");12Console.WriteLine(result);13var page = await browser.NewPageAsync();14var frame = await page.MainFrameAsync();15var result = await frame.EvaluateHandleAsync("() => document.body");16Console.WriteLine(result);17var page = await browser.NewPageAsync();18var frame = await page.MainFrameAsync();19await frame.FillAsync("input[name=q]", "hello");20var page = await browser.NewPageAsync();21var frame = await page.MainFrameAsync();22await frame.FocusAsync("input[name=q]");23var page = await browser.NewPageAsync();24var frame = await page.MainFrameAsync();25var result = await frame.GetAttributeAsync("input[name=q]", "value");26Console.WriteLine(result);
EvalOnSelectorAsync
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false });10 var page = await browser.NewPageAsync();11 var search = await page.QuerySelectorAsync("#searchInput");12 var value = await search.EvalOnSelectorAsync<string>("input", "input => input.value");13 Console.WriteLine(value);14 }15 }16}17public Task<T> EvalOnSelectorAsync<T>(string selector, string expression, object arg = null)
EvalOnSelectorAsync
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Threading.Tasks;4using Microsoft.Playwright;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 context = await browser.NewContextAsync();14 var page = await context.NewPageAsync();15 var input = await page.QuerySelectorAsync("input[name='search']");16 await input.TypeAsync("Playwright");17 var searchButton = await page.QuerySelectorAsync("button[type='submit']");18 await searchButton.ClickAsync();19 var elementHandle = await page.EvalOnSelectorAsync("a[href='/wiki/Playwright_(software)']", "(element) => element");20 await elementHandle.ClickAsync();21 await page.CloseAsync();22 }23 }24}
EvalOnSelectorAsync
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.EvaluateAsync(@"() => {12 var x = 1;13 var y = 2;14 var z = x + y;15 }");16 var handle = await page.EvalOnSelectorAsync(@"body", @"(element) => {17 return z;18 }");19 var value = await handle.JsonValueAsync();20 Console.WriteLine(value);21 }22 }23}
EvalOnSelectorAsync
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions10 {11 });12 var context = await browser.NewContextAsync();13 var page = await context.NewPageAsync();14 await page.ClickAsync("text=Sign in");15 await page.ClickAsync("text=Create account");16 await page.FillAsync("input[name=\"firstName\"]", "John");17 await page.FillAsync("input[name=\"lastName\"]", "Doe");18 await page.FillAsync("input[name=\"Username\"]", "johndoe");19 await page.FillAsync("input[name=\"Passwd\"]", "johndoe");20 await page.FillAsync("input[name=\"ConfirmPasswd\"]", "johndoe");21 await page.ClickAsync("text=Next");22 await page.ClickAsync("text=Next");23 await page.ClickAsync("text=I agree");24 await page.ClickAsync("text=Next");
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!!