Best Puppeteer-sharp code snippet using PuppeteerSharp.Worker.EvaluateExpressionAsync
PuppeteerBrowserBuilder.cs
Source:PuppeteerBrowserBuilder.cs
...488 return await page.EvaluateFunctionAsync<string>($"name => navigator.permissions.query({permissionName}).then(result => result.state)");489 }490 public async Task ScrollPageSync(Page page, TimeSpan stepDelay, int maxScroll = 40000, int step = 200)491 {492 var height = await page.EvaluateExpressionAsync<int>(@"document.body.scrollHeight");493 var x = 0;494 while (x < height && x <= maxScroll)495 {496 height = await page.EvaluateExpressionAsync<int>(@"document.body.scrollHeight");497 x += 200;498 await _delayService.DelayAsync(stepDelay);499 await page.EvaluateExpressionAsync($"window.scrollTo(0, {x});");500 }501 }502 private async Task<Page> GoToPageAsync(string stringUrl, TimeSpan? timeSpan, params WaitUntilNavigation[] waitUntilNavigations)503 {504 var page = await _browserContext.NewPageAsync();505 await page.SetCacheEnabledAsync(_puppeteerContext.PageCacheEnabled);506 await page.SetJavaScriptEnabledAsync(true);507 if (_puppeteerContext.PageEvents)508 {509 page.Error += Page_Error;510 page.PageError += Page_PageError;511 page.Console += Page_Info;512 page.Request += Page_Request;513 }...
PuppeteerDetector.cs
Source:PuppeteerDetector.cs
...113 // First, reload the page. This is necessary because service workers are often registered on an already-served page, so they might not be in the cache.114 await detectionResults.Page.ReloadAsync(serviceWorkerDetectionTimeoutMs, new[] { WaitUntilNavigation.Networkidle2 });115 // See if we have HTML in the cache. If so, we'll deem it offline-capable.116 // This is more resilient than futzing with offline mode and refreshing pages, which is fraught with race conditions.117 var isHtmlInCache = await detectionResults.Page.EvaluateExpressionAsync<bool>(@"118 async function isHtmlInCache() {119 const cacheNames = await caches.keys();120 for (let cacheName of cacheNames) {121 const cache = await caches.open(cacheName);122 const cacheKeys = await cache.keys();123 for (let key of cacheKeys) {124 const cachedObject = await cache.match(key);125 if (cachedObject && cachedObject.headers) {126 const contentType = cachedObject.headers.get('Content-Type');127 if (contentType && contentType.startsWith('text/html')) {128 return true;129 }130 }131 }132 }133 return false;134 }135 isHtmlInCache();136 ");137 138 analyticsService.LogOfflineResult(uri, isHtmlInCache);139 return isHtmlInCache;140 }141 catch (Exception evalError)142 {143 logger.LogError(evalError, "Unable to determine offline support due to evaluation error");144 return false;145 }146 }147 private async Task<bool> TryCheckPushRegistration(Page page, Uri uri)148 {149 try150 {151 return await CheckPushRegistration(page);152 }153 catch (Exception pushRegError)154 {155 logger.LogWarning(pushRegError, "Error fetching push registration for {url}", uri);156 return false;157 }158 }159 private Task<bool> CheckPushRegistration(Page page)160 {161 return page.EvaluateExpressionAsync<bool>("navigator.serviceWorker.getRegistration().then(swReg => swReg.pushManager.getSubscription()).then(pushReg => pushReg != null)");162 }163 private async Task<string> TryGetScriptContents(Uri? scriptUri, CancellationToken cancelToken)164 {165 if (scriptUri == null)166 {167 return string.Empty;168 }169 try170 {171 return await http.GetStringAsync(scriptUri, httpTimeout, cancelToken);172 }173 catch (TimeoutException)174 {175 logger.LogWarning("Cancelled fetch of script {url} because it took too long.");176 return string.Empty;177 }178 catch (Exception fetchError)179 {180 logger.LogWarning(fetchError, "Unable to load script contents due to error. Script was at {src}", scriptUri);181 return string.Empty;182 }183 }184 private async Task<bool> TryCheckBackgroundSync(Page page, Uri uri)185 {186 try187 {188 return await page.EvaluateExpressionAsync<bool>("navigator.serviceWorker.getRegistration().then(swReg => swReg.pushManager.getSubscription()).then(pushReg => pushReg != null)");189 }190 catch (Exception pushRegError)191 {192 logger.LogWarning(pushRegError, "Error fetching push registration for {url}", uri);193 return false;194 }195 }196 private async Task<Uri?> TryGetScope(Page page, Uri uri)197 {198 try199 {200 return await GetScope(page, uri);201 }202 catch (Exception scopeError)203 {204 logger.LogWarning(scopeError, "Error fetching scope of service worker for {url}", uri);205 return null;206 }207 }208 private async Task<Uri?> GetScope(Page page, Uri uri)209 {210 var scopeUrl = await page.EvaluateExpressionAsync<string>("navigator.serviceWorker.getRegistration().then(reg => reg.scope)");211 if (Uri.TryCreate(scopeUrl, UriKind.Absolute, out var scopeUri))212 {213 return scopeUri;214 }215 // Can we construct an absolute URI from the base URI?216 if (Uri.TryCreate(uri, scopeUrl, out var absoluteScopeUri))217 {218 return absoluteScopeUri;219 }220 logger.LogWarning("Scope evaluation succeeded, but scope was not a valid URI: {scopeUrl}", scopeUrl);221 return null;222 }223 private async Task<ServiceWorkerExistsResult> GetServiceWorkerUrl(Browser browser, Page page)224 {...
FacebookRegistration.cs
Source:FacebookRegistration.cs
...146 {147 //var targets = page.Browser.Targets();148 var anticaptchaScriptText = File.ReadAllText(Path.GetFullPath(".\\Data\\init.js"));149 anticaptchaScriptText = anticaptchaScriptText.Replace("YOUR-ANTI-CAPTCHA-API-KEY", AntiCaptchaOnlineApi.GetApiKeyAnticaptcha());150 await page.EvaluateExpressionAsync(anticaptchaScriptText);151 anticaptchaScriptText = File.ReadAllText(Path.GetFullPath(".\\Data\\recaptchaaifb.js"));152 await page.EvaluateExpressionAsync(anticaptchaScriptText);153 //targets[8].154 //await page.AddScriptTagAsync(new AddTagOptions { Content= anticaptchaScriptText });155 //await page.WaitForSelectorAsync(".antigate_solver.solved", new WaitForSelectorOptions { Timeout = 120 * 1000 });156 // await page.ClickAsync("input[type=submit]");157 //await page.WaitForNavigationAsync();158 try { await page.WaitForTimeoutAsync(90 * 1000); } catch { }159 await SolveRecaptcha(page, ++deep);160 }161 }162 private async Task ClickSubmit(Page page)163 {164 var elSignUp = await page.QuerySelectorAsync("button[type=submit]");165 await elSignUp.ClickAsync();166 await page.WaitForTimeoutAsync(500);167 }168 private async Task FillPhoneAgain(Page page)169 {170 var eSendCode = await page.QuerySelectorAsync("button[name='submit[set_contact_point_primary_button]']");171 if (eSendCode == null) return;172 var selCountries = "ul[role=menu] a>span>span";173 var eCountries = await page.QuerySelectorAllAsync(selCountries);174 if (eCountries == null) return;175 var jsAltMailList = $@"Array.from(document.querySelectorAll('{selCountries}')).map(a => a.innerText);";176 var countries = await page.EvaluateExpressionAsync<string[]>(jsAltMailList);177 // код ÑÑÑÐ°Ð½Ñ +44178 var country = countries.FirstOrDefault(z => z.Contains($"(+{_countryPrefix})"));179 var idx = Array.IndexOf(countries, country);180 if (eCountries.Length > idx) await eCountries[idx].ClickAsync();181 var ePhone = await page.QuerySelectorAsync("input[type=tel]");182 await ePhone.TypeAsync(_data.Phone.Replace($"+{_countryPrefix}", ""), _typeOptions);183 await eSendCode.ClickAsync();184 }185 #endregion186 #region else187 private async static Task SetHooks(Page page)188 {189 //await page.SetRequestInterceptionAsync(true);190 //page.Request += Page_Request;191 //page.Response += Page_Response;192 page.FrameAttached += Page_FrameAttached;193 page.FrameNavigated += Page_FrameNavigated;194 page.WorkerCreated += Page_WorkerCreated;195 }196 private static void Page_WorkerCreated(object sender, WorkerEventArgs e)197 {198 Log.Info($"{nameof(Page_WorkerCreated)} {e.Worker.Url}");199 }200 private async static void Page_FrameNavigated(object sender, FrameEventArgs e)201 {202 Log.Info($"{nameof(Page_FrameNavigated)} {e.Frame.Url}");203 //if (e.Frame.Url.Contains("referer_frame"))204 //{205 // var anticaptchaScriptText = File.ReadAllText(Path.GetFullPath(".\\Data\\recaptchaaifb.js"));206 // //await e.Frame.AddScriptTagAsync(new AddTagOptions { Url = "https://cdn.antcpt.com/imacros_inclusion/recaptcha.js" });207 // await e.Frame.AddScriptTagAsync(new AddTagOptions { Content = anticaptchaScriptText });208 //}209 }210 private async static void Page_FrameAttached(object sender, FrameEventArgs e)211 {212 Log.Info($"{nameof(Page_FrameAttached)} {e.Frame.Url}");213 //var anticaptchaScriptText = File.ReadAllText(Path.GetFullPath(".\\Data\\init.js"));214 //anticaptchaScriptText = anticaptchaScriptText.Replace("YOUR-ANTI-CAPTCHA-API-KEY", AntiCaptchaOnlineApi.GetApiKeyAnticaptcha());215 //await e.Frame.EvaluateExpressionAsync(anticaptchaScriptText);216 //anticaptchaScriptText = File.ReadAllText(Path.GetFullPath(".\\Data\\recaptchaaifb.js"));217 //await e.Frame.EvaluateExpressionAsync(anticaptchaScriptText);218 //await e.Frame.AddScriptTagAsync(new AddTagOptions { Url = "https://cdn.antcpt.com/imacros_inclusion/recaptcha.js" });219 }220 private static async void Page_Response(object sender, ResponseCreatedEventArgs e)221 {222 Log.Info($"Page_Response {e.Response.Request.Url}");223 if (e.Response.Request.Url.Contains("referer_frame"))224 {225 var body = await e.Response.TextAsync();226 //await e.Response.Request.RespondAsync(new ResponseData { Body = body });227 }228 }229 private static async void Page_Request(object sender, RequestEventArgs e)230 {231 //if (e.Request.Url.Contains("referer_frame"))...
TargetTests.cs
Source:TargetTests.cs
...48 // The pages will be the testing page and the original newtab page49 await using var browser = await Puppeteer.LaunchAsync(TestConstants.DefaultBrowserOptions());50 var allPages = await browser.PagesAsync();51 var originalPage = allPages.First(p => p != Page);52 Assert.Equal("Hello world", await originalPage.EvaluateExpressionAsync<string>("['Hello', 'world'].join(' ')"));53 Assert.NotNull(await originalPage.QuerySelectorAsync("body"));54 }55 [PuppeteerTest("target.spec.ts", "Target", "should report when a new page is created and closed")]56 [SkipBrowserFact(skipFirefox: true)]57 public async Task ShouldReportWhenANewPageIsCreatedAndClosed()58 {59 var otherPageTask = Context.WaitForTargetAsync(t => t.Url == TestConstants.CrossProcessUrl + "/empty.html")60 .ContinueWith(t => t.Result.PageAsync());61 await Task.WhenAll(62 otherPageTask,63 Page.EvaluateFunctionHandleAsync("url => window.open(url)", TestConstants.CrossProcessUrl + "/empty.html")64 );65 var otherPage = await otherPageTask.Result;66 Assert.Contains(TestConstants.CrossProcessUrl, otherPage.Url);67 Assert.Equal("Hello world", await otherPage.EvaluateExpressionAsync<string>("['Hello', 'world'].join(' ')"));68 Assert.NotNull(await otherPage.QuerySelectorAsync("body"));69 var allPages = await Context.PagesAsync();70 Assert.Contains(Page, allPages);71 Assert.Contains(otherPage, allPages);72 var closePageTaskCompletion = new TaskCompletionSource<Page>();73 async void TargetDestroyedEventHandler(object sender, TargetChangedArgs e)74 {75 closePageTaskCompletion.SetResult(await e.Target.PageAsync());76 Context.TargetDestroyed -= TargetDestroyedEventHandler;77 }78 Context.TargetDestroyed += TargetDestroyedEventHandler;79 await otherPage.CloseAsync();80 Assert.Equal(otherPage, await closePageTaskCompletion.Task);81 allPages = await Task.WhenAll(Context.Targets().Select(target => target.PageAsync()));82 Assert.Contains(Page, allPages);83 Assert.DoesNotContain(otherPage, allPages);84 }85 [PuppeteerTest("target.spec.ts", "Target", "should report when a service worker is created and destroyed")]86 [SkipBrowserFact(skipFirefox: true)]87 public async Task ShouldReportWhenAServiceWorkerIsCreatedAndDestroyed()88 {89 await Page.GoToAsync(TestConstants.EmptyPage);90 var createdTargetTaskCompletion = new TaskCompletionSource<Target>();91 void TargetCreatedEventHandler(object sender, TargetChangedArgs e)92 {93 createdTargetTaskCompletion.SetResult(e.Target);94 Context.TargetCreated -= TargetCreatedEventHandler;95 }96 Context.TargetCreated += TargetCreatedEventHandler;97 await Page.GoToAsync(TestConstants.ServerUrl + "/serviceworkers/empty/sw.html");98 var createdTarget = await createdTargetTaskCompletion.Task;99 Assert.Equal(TargetType.ServiceWorker, createdTarget.Type);100 Assert.Equal(TestConstants.ServerUrl + "/serviceworkers/empty/sw.js", createdTarget.Url);101 var targetDestroyedTaskCompletion = new TaskCompletionSource<Target>();102 void TargetDestroyedEventHandler(object sender, TargetChangedArgs e)103 {104 targetDestroyedTaskCompletion.SetResult(e.Target);105 Context.TargetDestroyed -= TargetDestroyedEventHandler;106 }107 Context.TargetDestroyed += TargetDestroyedEventHandler;108 await Page.EvaluateExpressionAsync("window.registrationPromise.then(registration => registration.unregister())");109 Assert.Equal(createdTarget, await targetDestroyedTaskCompletion.Task);110 }111 [PuppeteerTest("target.spec.ts", "Target", "should create a worker from a service worker")]112 [SkipBrowserFact(skipFirefox: true)]113 public async Task ShouldCreateAWorkerFromAServiceWorker()114 {115 await Page.GoToAsync(TestConstants.ServerUrl + "/serviceworkers/empty/sw.html");116 var target = await Context.WaitForTargetAsync(t => t.Type == TargetType.ServiceWorker);117 var worker = await target.WorkerAsync();118 Assert.Equal("[object ServiceWorkerGlobalScope]", await worker.EvaluateFunctionAsync("() => self.toString()"));119 }120 [PuppeteerTest("target.spec.ts", "Target", "should create a worker from a shared worker")]121 [SkipBrowserFact(skipFirefox: true)]122 public async Task ShouldCreateAWorkerFromASharedWorker()...
NavigateCollect.cs
Source:NavigateCollect.cs
...158 return -1;159 }160 private async Task GoToPage(int x)161 {162 await this.Page.EvaluateExpressionAsync($"updateTableAfterSelectingPage(\"{x}\",false)");163 await this.Page.EvaluateExpressionAsync($"updateWhat()");164 var loader1 = Retry<Task>(165 async () =>166 {167 var loader = await this.Page.QuerySelectorAsync("div#contentLoading");168 var result = await this.Page.WaitForFunctionAsync($"el => el.outerHTML.includes('none')", new WaitForFunctionOptions { Polling = WaitForFunctionPollingOption.Mutation, Timeout = this.DefaultTimeout }, loader);169 }, 2,170 $"[Page] Wait till load complete");171 var loader2 = Retry<Task>(172 async () =>173 {174 var loader = await this.Page.QuerySelectorAsync("div#loading");175 var result = await this.Page.WaitForFunctionAsync($"el => el.outerHTML.includes('none')", new WaitForFunctionOptions { Polling = WaitForFunctionPollingOption.Mutation, Timeout = this.DefaultTimeout }, loader);176 }, 2,177 $"[Page] Wait till load complete");178 await Task.WhenAll(loader1, loader2);179 await this.UnblockOwners();180 }181 private async Task UnblockOwners()182 {183 bool success = false;184 await this.Page.WaitForTimeoutAsync(this.DefaultTimeout);185 var items = await this.Page.XPathAsync("//td[@class='uncopyable']");186 if (items != null)187 {188 await this.Page.EvaluateExpressionAsync("var elements = document.getElementsByClassName('uncopyable');for (var i = 0; i < elements.length; i++) { elements[i].innerHTML = elements[i].getAttribute('uncopyable-content');}");189 await this.Page.WaitForTimeoutAsync(this.DefaultTimeout);190 var item1 = items[0];191 var innerhtml = await this.Page.EvaluateFunctionAsync<string>("el => el.innerHTML", item1);192 if (!innerhtml.Equals(string.Empty))193 {194 success = true;195 }196 }197 if (!success)198 {199 throw new Exception("NavigateCollect: Failed to unblock owner text");200 }201 }202 private async Task ProcessAsync()203 {204 await this.Page.WaitForTimeoutAsync(this.DefaultTimeout);205 string HTML = await this.Page.GetContentAsync();206 try207 {208 var openScraping = new StructuredDataExtractor(this.config);209 var scrapingResults = openScraping.Extract(html: HTML);210 var records = scrapingResults.ToObject<Model.RootObject>();211 if (records.PropertyRecords.Count > 0)212 {213 var first = records.PropertyRecords.First().Owner;214 var last = records.PropertyRecords.Last().Owner;215 if (string.IsNullOrEmpty(first) && string.IsNullOrEmpty(last))216 {217 // suspicious218 HTML = null;219 }220 else221 {222 return;223 }224 }225 else226 {227 HTML = null;228 }229 }230 catch (Exception ex)231 {232 HTML = null;233 throw ex;234 }235 if (HTML.Equals(null))236 {237 throw new Exception("NavigateCollect: No record data was returned");238 }239 }240 private async Task InitialiseAsync()241 {242 if (this.Page == null)243 {244 throw new NullReferenceException("NavigateSearch: Puppeteer.Page instance is null");245 }246 if (!this.Page.Url.StartsWith(this.targetpage))247 {248 await this.Page.SetExtraHttpHeadersAsync(new Dictionary<string, string>() { { "Referrer", "https://www.property-guru.co.nz/gurux/" } });249 await Retry<Task>(async () => { await this.Page.GoToAsync(this.targetpage, new NavigationOptions { Timeout = this.DefaultTimeout, WaitUntil = new[] { WaitUntilNavigation.DOMContentLoaded } }); }, 3, $"[Navigation] {this.workerid}");250 await this.Page.WaitForTimeoutAsync(this.DefaultTimeout);251 }252 var name = await this.Page.EvaluateExpressionAsync<string>("analytics._user._getTraits().name");253 if (name.Length > 0)254 {255 Console.WriteLine($"[ {DateTime.Now.ToShortTimeString()} ] User is logged in.");256 this.LoggedIn = true;257 }258 if (!this.LoggedIn)259 {260 throw new Exception("NavigateCollect: Login oracle was not found - User is logged out");261 }262 this.totalpages = await this.GetTotalPages();263 if (this.IsOffset)264 {265 await this.GoToPage(this.offset);266 }...
Worker.cs
Source:Worker.cs
...71 /// <param name="script">Script to be evaluated in browser context</param>72 /// <remarks>73 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.74 /// </remarks>75 /// <seealso cref="ExecutionContext.EvaluateExpressionAsync(string)"/>76 /// <returns>Task which resolves to script return value</returns>77 public async Task<T> EvaluateExpressionAsync<T>(string script)78 => await (await ExecutionContextTask.ConfigureAwait(false)).EvaluateExpressionAsync<T>(script).ConfigureAwait(false);79 /// <summary>80 /// Executes a script in browser context81 /// </summary>82 /// <param name="script">Script to be evaluated in browser context</param>83 /// <remarks>84 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.85 /// </remarks>86 /// <returns>Task which resolves to script return value</returns>87 /// <seealso cref="ExecutionContext.EvaluateExpressionHandleAsync(string)"/>88 public async Task<JSHandle> EvaluateExpressionHandleAsync(string script)89 => await (await ExecutionContextTask.ConfigureAwait(false)).EvaluateExpressionHandleAsync(script).ConfigureAwait(false);90 internal Task<ExecutionContext> ExecutionContextTask => _executionContextCallback.Task;91 internal async void OnMessageReceived(object sender, MessageEventArgs e)92 {...
PageWorkerTests.cs
Source:PageWorkerTests.cs
...24 workerCreatedTcs.Task,25 Page.GoToAsync(TestConstants.ServerUrl + "/worker/worker.html"));26 var worker = Page.Workers[0];27 Assert.Contains("worker.js", worker.Url);28 Assert.Equal("worker function result", await worker.EvaluateExpressionAsync<string>("self.workerFunction()"));29 await Page.GoToAsync(TestConstants.EmptyPage);30 await workerDestroyedTcs.Task.WithTimeout();31 Assert.Empty(Page.Workers);32 }33 [PuppeteerTest("worker.spec.ts", "Workers", "should emit created and destroyed events")]34 [SkipBrowserFact(skipFirefox: true)]35 public async Task ShouldEmitCreatedAndDestroyedEvents()36 {37 var workerCreatedTcs = new TaskCompletionSource<Worker>();38 Page.WorkerCreated += (_, e) => workerCreatedTcs.TrySetResult(e.Worker);39 var workerObj = await Page.EvaluateFunctionHandleAsync("() => new Worker('data:text/javascript,1')");40 var worker = await workerCreatedTcs.Task;41 var workerDestroyedTcs = new TaskCompletionSource<Worker>();42 Page.WorkerDestroyed += (_, e) => workerDestroyedTcs.TrySetResult(e.Worker);43 await Page.EvaluateFunctionAsync("workerObj => workerObj.terminate()", workerObj);44 Assert.Same(worker, await workerDestroyedTcs.Task);45 }46 [PuppeteerTest("worker.spec.ts", "Workers", "should report console logs")]47 [SkipBrowserFact(skipFirefox: true)]48 public async Task ShouldReportConsoleLogs()49 {50 var consoleTcs = new TaskCompletionSource<ConsoleMessage>();51 Page.Console += (_, e) => consoleTcs.TrySetResult(e.Message);52 await Page.EvaluateFunctionAsync("() => new Worker(`data:text/javascript,console.log(1)`)");53 var log = await consoleTcs.Task;54 Assert.Equal("1", log.Text);55 Assert.Equal(new ConsoleMessageLocation56 {57 URL = "",58 LineNumber = 0,59 ColumnNumber = 860 }, log.Location);61 }62 [PuppeteerTest("worker.spec.ts", "Workers", "should have JSHandles for console logs")]63 [SkipBrowserFact(skipFirefox: true)]64 public async Task ShouldHaveJSHandlesForConsoleLogs()65 {66 var consoleTcs = new TaskCompletionSource<ConsoleMessage>();67 Page.Console += (_, e) =>68 {69 consoleTcs.TrySetResult(e.Message);70 };71 await Page.EvaluateFunctionAsync("() => new Worker(`data:text/javascript,console.log(1, 2, 3, this)`)");72 var log = await consoleTcs.Task;73 Assert.Equal("1 2 3 JSHandle@object", log.Text);74 Assert.Equal(4, log.Args.Count);75 var json = await (await log.Args[3].GetPropertyAsync("origin")).JsonValueAsync<object>();76 Assert.Equal("null", json);77 }78 [PuppeteerTest("worker.spec.ts", "Workers", "should have an execution context")]79 [SkipBrowserFact(skipFirefox: true)]80 public async Task ShouldHaveAnExecutionContext()81 {82 var workerCreatedTcs = new TaskCompletionSource<Worker>();83 Page.WorkerCreated += (_, e) => workerCreatedTcs.TrySetResult(e.Worker);84 await Page.EvaluateFunctionAsync("() => new Worker(`data:text/javascript,console.log(1)`)");85 var worker = await workerCreatedTcs.Task;86 Assert.Equal(2, await worker.EvaluateExpressionAsync<int>("1+1"));87 }88 [PuppeteerTest("worker.spec.ts", "Workers", "should report errors")]89 [SkipBrowserFact(skipFirefox: true)]90 public async Task ShouldReportErrors()91 {92 var errorTcs = new TaskCompletionSource<string>();93 Page.PageError += (_, e) => errorTcs.TrySetResult(e.Message);94 await Page.EvaluateFunctionAsync("() => new Worker(`data:text/javascript, throw new Error('this is my error');`)");95 var errorLog = await errorTcs.Task;96 Assert.Contains("this is my error", errorLog);97 }98 }99}...
WorkerTests.cs
Source:WorkerTests.cs
...21 workerCreatedTcs.Task,22 Page.GoToAsync(TestConstants.ServerUrl + "/worker/worker.html"));23 var worker = Page.Workers[0];24 Assert.Contains("worker.js", worker.Url);25 Assert.Equal("worker function result", await worker.EvaluateExpressionAsync<string>("self.workerFunction()"));26 await Page.GoToAsync(TestConstants.EmptyPage);27 await workerDestroyedTcs.Task.WithTimeout();28 Assert.Empty(Page.Workers);29 }30 [Fact]31 public async Task ShouldEmitCreatedAndDestroyedEvents()32 {33 var workerCreatedTcs = new TaskCompletionSource<Worker>();34 Page.WorkerCreated += (sender, e) => workerCreatedTcs.TrySetResult(e.Worker);35 var workerObj = await Page.EvaluateFunctionHandleAsync("() => new Worker('data:text/javascript,1')");36 var worker = await workerCreatedTcs.Task;37 var workerDestroyedTcs = new TaskCompletionSource<Worker>();38 Page.WorkerDestroyed += (sender, e) => workerDestroyedTcs.TrySetResult(e.Worker);39 await Page.EvaluateFunctionAsync("workerObj => workerObj.terminate()", workerObj);40 Assert.Same(worker, await workerDestroyedTcs.Task);41 }42 [Fact]43 public async Task ShouldReportConsoleLogs()44 {45 var consoleTcs = new TaskCompletionSource<ConsoleMessage>();46 Page.Console += (sender, e) => consoleTcs.TrySetResult(e.Message);47 await Page.EvaluateFunctionAsync("() => new Worker(`data:text/javascript,console.log(1)`)");48 var log = await consoleTcs.Task;49 Assert.Equal("1", log.Text);50 Assert.Equal(new ConsoleMessageLocation51 {52 URL = "data:text/javascript,console.log(1)",53 LineNumber = 0,54 ColumnNumber = 855 }, log.Location);56 }57 [Fact]58 public async Task ShouldHaveJSHandlesForConsoleLogs()59 {60 var consoleTcs = new TaskCompletionSource<ConsoleMessage>();61 Page.Console += (sender, e) =>62 {63 consoleTcs.TrySetResult(e.Message);64 };65 await Page.EvaluateFunctionAsync("() => new Worker(`data:text/javascript,console.log(1, 2, 3, this)`)");66 var log = await consoleTcs.Task;67 Assert.Equal("1 2 3 JSHandle@object", log.Text);68 Assert.Equal(4, log.Args.Count);69 var json = await (await log.Args[3].GetPropertyAsync("origin")).JsonValueAsync<object>();70 Assert.Equal("null", json);71 }72 [Fact]73 public async Task ShouldHaveAnExecutionContext()74 {75 var workerCreatedTcs = new TaskCompletionSource<Worker>();76 Page.WorkerCreated += (sender, e) => workerCreatedTcs.TrySetResult(e.Worker);77 await Page.EvaluateFunctionAsync("() => new Worker(`data:text/javascript,console.log(1)`)");78 var worker = await workerCreatedTcs.Task;79 Assert.Equal(2, await worker.EvaluateExpressionAsync<int>("1+1"));80 }81 [Fact]82 public async Task ShouldReportErrors()83 {84 var errorTcs = new TaskCompletionSource<string>();85 Page.PageError += (sender, e) => errorTcs.TrySetResult(e.Message);86 await Page.EvaluateFunctionAsync("() => new Worker(`data:text/javascript, throw new Error('this is my error');`)");87 var errorLog = await errorTcs.Task;88 Assert.Contains("this is my error", errorLog);89 }90 }91}...
EvaluateExpressionAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args)7 {8 MainAsync().Wait();9 }10 stti async Task MainAsync()11 {12 var browsr = awaiteter.LaunchAsync(new LaunchOpions13 {14 });15 var page = await brows.NewPageAsync();16 await page.EvaluateExpressionAsync("document.queryelector('input[name=\"q\"]').value = \"Puppeteer\"");17 await page.ClickAsync("input[name=\"btnK\"]");18 await page.WaitForNavigationAsync();19 await page.WaitForSelectorAsync("div#searc");20 vr esult = await page.EvaluateExressionAsync("document.querySelector('div#search').innerText");21 Console.WriteLine(result.ToString());22 browser.Close();23 }24 }25}
EvaluateExpressionAsync
Using AI Code Generation
1using System;2using System.hrading.Tasks;3uing PuppeeerSharp;4{5 {6 static void Main(string[] args)7 {8 MainAsync().Wait();9 }10 static async Task MainAsync()11 {12 var browser = await Puppeteer.LaunchAsync(new LaunchOptions13 {14 });15 var page = await browser.NewPageAsync();16 await page.EvaluateExpressionAsync("document.querySelector('input[name=\"q\"]').value = \"Puppeteer\"");17 await page.ClickAsync("input[name=\"btnK\"]");18 await page.WaitForNavigationAsync();19 await page.WaitForSelectorAsync("div#search");20 var result = await page.EvaluateExpressionAsync("document.querySelector('div#search').innerText");21 Console.WriteLine(result.ToString());22 browser.Close();23 }24 }25}
EvaluateExpressionAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 });11 var page = await browser.NewPageAsync();12 var worker = await page.EvaluateExpressionAsync<Worker>("() => new Worker('worker.js')");13 var result = await worker.EvaluateExpressionAsync<int>("1 + 2");14 Console.WriteLine(result);15 await browser.CloseAsync();16 }17 }18{19}Headless=false,20Args=new string[] "--no-sandbox" }21});22var/page/= awaitPbrowser.NewPageAsync();23awaittpage.EvaluateExpressionAsync("document.body.innerHTML = '<h1>Hello World</h1>'");24await page.ScreenshotAsync("screenshot.png");25await browser.CloseAsync();26var browser = await Puppeteer.LaunchAsync(new LaunchOptions27{28 Args = new string[] { "--no-sandbox" }29});30var page = await browser.NewPageAsync();31awaitepage.EvaluateExpressionAsync("document.body.innerHTMLr=.'<h1>jello World</h1>'");32await page.ScreenshotAsync("scresnshot.png");33awit browser.CloseAsync();34var browser awai Puppetee.LanchAsync(nw LaunchOptions35{36 Args = new string[] { "--no-sandbox" }37});38var/page/=cawaitobrowser.NewPageAsync();39awaitepage.MainFrame.EvaluateExpressionAsync("document.body.innerHTML =t'<h1>HellooWorld</h1>'");40await page.ScreenshotAsync("screenshot.png");41awaitubrowser.CloseAsync();42var irowser = await Puppeteer.LaunchAsync(new LaunchOptions43{44 Args = new string[] { "--no-sandbox" }45});46var page = await browser.NtweageAsync();47await page.MainFrame.EvalunteExpressionAsync("documene.body.innerHTML = '<h1>Hello World</r1>'");48var elementHandle m await page.QuerySelectorAsync("h1");49awaiteelementHandle.EvaluateExpressionAsync("this.innerText = 'Hello World'");50await page.ScreenshotAsync("screenshot.png");51await browser.CloseAsync();52var browser = await Puppeteer.LaunchAsync(new LaunchOptions53{
EvaluateExpressionAsync
Using AI Code Generation
1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2 {3addEventListener('message', function (e) {4 postMessage(e.data + 1);5});6using System;7using System.Threading.Tasks;8using PuppeteerSharp;9{10 {11 static async Task Main(string[] args)12 {13 var browser = await Puppeteer.LaunchAsync(new LaunchOptions14 {15 });16 var page = await browser.NewPageAsync();17 var worker = await page.EvaluateExpressionAsync<Worker>("() => new Worker('worker.js')");18 var result = await worker.EvaluateExpressionAsync<int>("1 + 2");19 Console.WriteLine(result);20 await browser.CloseAsync();21 }22 }23}24addEventListener('message
EvaluateExpressionAsync
Using AI Code Generation
1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2 {3 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",4 Args = new string[] { "--no-sandbox" }5 });6 var page = await browser.NewPageAsync();7 var worker = await page.WaitForWorkerAsync();8 var result = await worker.EvaluateExpressionAsync<int>("1+2");9 Console.WriteLine(result);10 await browser.CloseAsync();11var browser = await Puppeteer.LaunchAsync(new LaunchOptions12 {13 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",14 Args = new string[] { "--no-sandbox" }15 });16 var page = await browser.NewPageAsync();17 var worker = await page.WaitForWorkerAsync();18 var result = await worker.EvaluateExpressionAsync<string>("'Hello World'");19 Console.WriteLine(result);20 await browser.CloseAsync();21var browser = await Puppeteer.LaunchAsync(new LaunchOptions22 {23 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",24 Args = new string[] { "--no-sandbox" }25 });26 var page = await browser.NewPageAsync();27 var worker = await page.WaitForWorkerAsync();28 var result = await worker.EvaluateExpressionAsync<int>("1+2");29 Console.WriteLine(result);30 await browser.CloseAsync();31var browser = await Puppeteer.LaunchAsync(new LaunchOptions32 {33 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",34 Args = new string[] { "--no-sandbox
EvaluateExpressionAsync
Using AI Code Generation
1using PuppeteerSharp;2using System.Threading.Tasks;3{4 {5 static async Task Main(string[] args)6 {7 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);8 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))9 using (var page = await browser.NewPageAsync())10 {11 var worker = await page.WaitForWorkerAsync();12 var result = await worker.EvaluateExpressionAsync<int>("2 + 3");13 System.Console.WriteLine(result);14 }15 }16 }17}
EvaluateExpressionAsync
Using AI Code Generation
1var page = await browser.NewPageAsync();2await page.SetContentAsync(@"3 var worker = new Worker('worker.js');4 worker.onmessage = function(e) {5 document.body.appendChild(document.createTextNode(e.data));6 }7");8await page.EvaluateExpressionAsync(@"9 worker.postMessage('hello');10");11await page.WaitForSelectorAsync("text=hello");12onmessage = function(e) {13 postMessage('hello');14};15var page = await browser.NewPageAsync();16await page.SetContentAsync(@"17 var worker = new Worker('worker.js');18 worker.onmessage = function(e) {19 document.body.appendChild(document.createTextNode(e.data));20 }21");22await page.EvaluateExpressionAsync(@"23 worker.postMessage('hello');24");25await page.WaitForSelectorAsync("text=hello");26onmessage = function(e) {27 postMessage('hello');28};29var page = await browser.NewPageAsync();30await page.SetContentAsync(@"31 var worker = new Worker('worker.js');32 worker.onmessage = function(e) {33 document.body.appendChild(document.createTextNode(e.data));34 }
EvaluateExpressionAsync
Using AI Code Generation
1var page = awaitbrowser.NewPageAsync();2vr= await page.WaitForServieWrkerAsyc();3var result = await worker.EvaluaEpressionAsync("navigator.serviceWorker.conrollerscriptURL");4Console.WriteLine(result.ToString());");5await page.CloseAsync();6var page = await browsei.NewPageAsync();7var worker = await page.WaitForServiceWorkerAsync();8var result = await worker.EvaluateExpressionAsync("navigator.serviceWorker.controller.scriptURL");9Console.WriteLine(result.ToString());10await page.CloseAsync();11var page = await browser.NewPageAsync();12var worker = await page.WaitForServiceWorkerAsync();13var result = await worker.EvaluateExpressionAsync("navigator.serviceWorker.controller.scriptURL"); worker.postMessage('hello');14Console.WriteLine(result."oString());15await page.CloseAsync();16var pae = await bowser.NewPgeAsync();17var worker = await page.WaitForServiceWorkerAsync();18var result = await worker.EvaluateExpressionAsync("navigator.serviceWorker.controller.scriptURL");19Console.WriteLine(result.ToString());await page.WaitForSelectorAsync("text=hello");20await page.CloseAsync();21var page = await browser.NewPageAsync();22var result = await worker.EvaluateExpressionAsync("navigator.serviceWorker.controller.scriptU/L");23Console.WriteLine(result.ToString());24await page.CloseAsync();25onmessage = function(e) {26 postMessage('hello');27};28var page = await browser.NewPageAsync();29await page.SetContentAsync(@"30 var worker = new Worker('worker
EvaluateExpressionAsync
Using AI Code Generation
1var page = await browser.NewPageAsync();2var worker = await page.WaitForServiceWorkerAsync();3var result = await worker.EvaluateExpressionAsync("navigator.serviceWorker.controller.scriptURL");4Console.WriteLine(result.ToString());5await page.CloseAsync();6var page = await browser.NewPageAsync();7var worker = await page.WaitForServiceWorkerAsync();8var result = await worker.EvaluateExpressionAsync("navigator.serviceWorker.controller.scriptURL");9Console.WriteLine(result.ToString());10await page.CloseAsync();11var page = await browser.NewPageAsync();12var worker = await page.WaitForServiceWorkerAsync();13var result = await worker.EvaluateExpressionAsync("navigator.serviceWorker.controller.scriptURL");14Console.WriteLine(result.ToString());15await page.CloseAsync();16var page = await browser.NewPageAsync();17var worker = await page.WaitForServiceWorkerAsync();18var result = await worker.EvaluateExpressionAsync("navigator.serviceWorker.controller.scriptURL");19Console.WriteLine(result.ToString());20await page.CloseAsync();21var page = await browser.NewPageAsync();22var worker = await page.WaitForServiceWorkerAsync();23var result = await worker.EvaluateExpressionAsync("navigator.serviceWorker.controller.scriptURL");24Console.WriteLine(result.ToString());25await page.CloseAsync();
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!