Best Puppeteer-sharp code snippet using PuppeteerSharp.Frame.EvaluateFunctionHandleAsync
Frame.cs
Source:Frame.cs
...207 var context = await GetExecutionContextAsync().ConfigureAwait(false);208 return await context.EvaluateExpressionHandleAsync(script).ConfigureAwait(false);209 }210 /// <summary>211 /// Passes a function to the <see cref="ExecutionContext.EvaluateFunctionAsync(string, object[])"/>, returns a <see cref="Task"/>, then <see cref="ExecutionContext.EvaluateFunctionHandleAsync(string, object[])"/> would wait for the <see cref="Task"/> to resolve and return its value.212 /// </summary>213 /// <example>214 /// <code>215 /// var frame = page.MainFrame;216 /// const handle = Page.MainFrame.EvaluateFunctionHandleAsync("() => Promise.resolve(self)");217 /// return handle; // Handle for the global object.218 /// </code>219 /// <see cref="JSHandle"/> instances can be passed as arguments to the <see cref="ExecutionContext.EvaluateFunctionAsync(string, object[])"/>:220 /// 221 /// const handle = await Page.MainFrame.EvaluateExpressionHandleAsync("document.body");222 /// const resultHandle = await Page.MainFrame.EvaluateFunctionHandleAsync("body => body.innerHTML", handle);223 /// return await resultHandle.JsonValueAsync(); // prints body's innerHTML224 /// </example>225 /// <returns>Resolves to the return value of <paramref name="function"/></returns>226 /// <param name="function">Function to be evaluated in the <see cref="ExecutionContext"/></param>227 /// <param name="args">Arguments to pass to <paramref name="function"/></param>228 public async Task<JSHandle> EvaluateFunctionHandleAsync(string function, params object[] args)229 {230 var context = await GetExecutionContextAsync().ConfigureAwait(false);231 return await context.EvaluateFunctionHandleAsync(function, args).ConfigureAwait(false);232 }233 /// <summary>234 /// Gets the <see cref="ExecutionContext"/> associated with the frame.235 /// </summary>236 /// <returns><see cref="ExecutionContext"/> associated with the frame.</returns>237 public Task<ExecutionContext> GetExecutionContextAsync() => _contextResolveTaskWrapper.Task;238 /// <summary>239 /// Waits for a selector to be added to the DOM240 /// </summary>241 /// <param name="selector">A selector of an element to wait for</param>242 /// <param name="options">Optional waiting parameters</param>243 /// <returns>A task that resolves when element specified by selector string is added to DOM</returns>244 /// <seealso cref="WaitForXPathAsync(string, WaitForSelectorOptions)"/>245 /// <seealso cref="Page.WaitForSelectorAsync(string, WaitForSelectorOptions)"/>246 /// <exception cref="WaitTaskTimeoutException">If timeout occurred.</exception>247 public Task<ElementHandle> WaitForSelectorAsync(string selector, WaitForSelectorOptions options = null)248 => WaitForSelectorOrXPathAsync(selector, false, options);249 /// <summary>250 /// Waits for a selector to be added to the DOM251 /// </summary>252 /// <param name="xpath">A xpath selector of an element to wait for</param>253 /// <param name="options">Optional waiting parameters</param>254 /// <returns>A task that resolves when element specified by selector string is added to DOM</returns>255 /// <example>256 /// <code>257 /// <![CDATA[258 /// var browser = await Puppeteer.LaunchAsync(new LaunchOptions());259 /// var page = await browser.NewPageAsync();260 /// string currentURL = null;261 /// page.MainFrame262 /// .WaitForXPathAsync("//img")263 /// .ContinueWith(_ => Console.WriteLine("First URL with image: " + currentURL));264 /// foreach (var current in new[] { "https://example.com", "https://google.com", "https://bbc.com" })265 /// {266 /// currentURL = current;267 /// await page.GoToAsync(currentURL);268 /// }269 /// await browser.CloseAsync();270 /// ]]>271 /// </code>272 /// </example>273 /// <seealso cref="WaitForSelectorAsync(string, WaitForSelectorOptions)"/>274 /// <seealso cref="Page.WaitForXPathAsync(string, WaitForSelectorOptions)"/>275 /// <exception cref="WaitTaskTimeoutException">If timeout occurred.</exception>276 public Task<ElementHandle> WaitForXPathAsync(string xpath, WaitForSelectorOptions options = null)277 => WaitForSelectorOrXPathAsync(xpath, true, options);278 /// <summary>279 /// Waits for a timeout280 /// </summary>281 /// <param name="milliseconds"></param>282 /// <returns>A task that resolves when after the timeout</returns>283 /// <seealso cref="Page.WaitForTimeoutAsync(int)"/>284 /// <exception cref="WaitTaskTimeoutException">If timeout occurred.</exception>285 public Task WaitForTimeoutAsync(int milliseconds) => Task.Delay(milliseconds);286 /// <summary>287 /// Waits for a function to be evaluated to a truthy value288 /// </summary>289 /// <param name="script">Function to be evaluated in browser context</param>290 /// <param name="options">Optional waiting parameters</param>291 /// <param name="args">Arguments to pass to <c>script</c></param>292 /// <returns>A task that resolves when the <c>script</c> returns a truthy value</returns>293 /// <seealso cref="Page.WaitForFunctionAsync(string, WaitForFunctionOptions, object[])"/>294 /// <exception cref="WaitTaskTimeoutException">If timeout occurred.</exception>295 public Task<JSHandle> WaitForFunctionAsync(string script, WaitForFunctionOptions options, params object[] args)296 => new WaitTask(this, script, false, "function", options.Polling, options.PollingInterval, options.Timeout, args).Task;297 /// <summary>298 /// Waits for an expression to be evaluated to a truthy value299 /// </summary>300 /// <param name="script">Expression to be evaluated in browser context</param>301 /// <param name="options">Optional waiting parameters</param>302 /// <returns>A task that resolves when the <c>script</c> returns a truthy value</returns>303 /// <seealso cref="Page.WaitForExpressionAsync(string, WaitForFunctionOptions)"/>304 /// <exception cref="WaitTaskTimeoutException">If timeout occurred.</exception>305 public Task<JSHandle> WaitForExpressionAsync(string script, WaitForFunctionOptions options)306 => new WaitTask(this, script, true, "function", options.Polling, options.PollingInterval, options.Timeout).Task;307 /// <summary>308 /// Triggers a change and input event once all the provided options have been selected. 309 /// If there's no <![CDATA[<select>]]> element matching selector, the method throws an error.310 /// </summary>311 /// <exception cref="SelectorException">If there's no element matching <paramref name="selector"/></exception>312 /// <param name="selector">A selector to query page for</param>313 /// <param name="values">Values of options to select. If the <![CDATA[<select>]]> has the multiple attribute, 314 /// all values are considered, otherwise only the first one is taken into account.</param>315 /// <returns>Returns an array of option values that have been successfully selected.</returns>316 /// <seealso cref="Page.SelectAsync(string, string[])"/>317 public Task<string[]> SelectAsync(string selector, params string[] values)318 => QuerySelectorAsync(selector).EvaluateFunctionAsync<string[]>(@"(element, values) => {319 if (element.nodeName.toLowerCase() !== 'select')320 throw new Error('Element is not a <select> element.');321 const options = Array.from(element.options);322 element.value = undefined;323 for (const option of options) {324 option.selected = values.includes(option.value);325 if (option.selected && !element.multiple)326 break;327 }328 element.dispatchEvent(new Event('input', { 'bubbles': true }));329 element.dispatchEvent(new Event('change', { 'bubbles': true }));330 return options.filter(option => option.selected).map(option => option.value);331 }", new[] { values });332 /// <summary>333 /// Queries frame for the selector. If there's no such element within the frame, the method will resolve to <c>null</c>.334 /// </summary>335 /// <param name="selector">Selector to query frame for</param>336 /// <returns>Task which resolves to <see cref="ElementHandle"/> pointing to the frame element</returns>337 /// <seealso cref="Page.QuerySelectorAsync(string)"/>338 public async Task<ElementHandle> QuerySelectorAsync(string selector)339 {340 var document = await GetDocument().ConfigureAwait(false);341 var value = await document.QuerySelectorAsync(selector).ConfigureAwait(false);342 return value;343 }344 /// <summary>345 /// Queries frame for the selector. If no elements match the selector, the return value resolve to <see cref="Array.Empty{T}"/>.346 /// </summary>347 /// <param name="selector">A selector to query frame for</param>348 /// <returns>Task which resolves to ElementHandles pointing to the frame elements</returns>349 /// <seealso cref="Page.QuerySelectorAllAsync(string)"/>350 public async Task<ElementHandle[]> QuerySelectorAllAsync(string selector)351 {352 var document = await GetDocument().ConfigureAwait(false);353 var value = await document.QuerySelectorAllAsync(selector).ConfigureAwait(false);354 return value;355 }356 /// <summary>357 /// Evaluates the XPath expression358 /// </summary>359 /// <param name="expression">Expression to evaluate <see href="https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate"/></param>360 /// <returns>Task which resolves to an array of <see cref="ElementHandle"/></returns>361 /// <seealso cref="Page.XPathAsync(string)"/>362 public async Task<ElementHandle[]> XPathAsync(string expression)363 {364 var document = await GetDocument().ConfigureAwait(false);365 var value = await document.XPathAsync(expression).ConfigureAwait(false);366 return value;367 }368 /// <summary>369 /// Adds a <c><![CDATA[<link rel="stylesheet">]]></c> tag into the page with the desired url or a <c><![CDATA[<link rel="stylesheet">]]></c> tag with the content370 /// </summary>371 /// <param name="options">add style tag options</param>372 /// <returns>Task which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame</returns>373 /// <seealso cref="Page.AddStyleTagAsync(AddTagOptions)"/>374 /// <seealso cref="Page.AddStyleTagAsync(string)"/>375 public async Task<ElementHandle> AddStyleTag(AddTagOptions options)376 {377 const string addStyleUrl = @"async function addStyleUrl(url) {378 const link = document.createElement('link');379 link.rel = 'stylesheet';380 link.href = url;381 const promise = new Promise((res, rej) => {382 link.onload = res;383 link.onerror = rej;384 });385 document.head.appendChild(link);386 await promise;387 return link;388 }";389 const string addStyleContent = @"async function addStyleContent(content) {390 const style = document.createElement('style');391 style.type = 'text/css';392 style.appendChild(document.createTextNode(content));393 const promise = new Promise((res, rej) => {394 style.onload = res;395 style.onerror = rej;396 });397 document.head.appendChild(style);398 await promise;399 return style;400 }";401 if (!string.IsNullOrEmpty(options.Url))402 {403 var url = options.Url;404 try405 {406 var context = await GetExecutionContextAsync().ConfigureAwait(false);407 return (await context.EvaluateFunctionHandleAsync(addStyleUrl, url).ConfigureAwait(false)) as ElementHandle;408 }409 catch (PuppeteerException)410 {411 throw new PuppeteerException($"Loading style from {url} failed");412 }413 }414 if (!string.IsNullOrEmpty(options.Path))415 {416 var contents = await AsyncFileHelper.ReadAllText(options.Path).ConfigureAwait(false);417 contents += "//# sourceURL=" + options.Path.Replace("\n", string.Empty);418 var context = await GetExecutionContextAsync().ConfigureAwait(false);419 return (await context.EvaluateFunctionHandleAsync(addStyleContent, contents).ConfigureAwait(false)) as ElementHandle;420 }421 if (!string.IsNullOrEmpty(options.Content))422 {423 var context = await GetExecutionContextAsync().ConfigureAwait(false);424 return (await context.EvaluateFunctionHandleAsync(addStyleContent, options.Content).ConfigureAwait(false)) as ElementHandle;425 }426 throw new ArgumentException("Provide options with a `Url`, `Path` or `Content` property");427 }428 /// <summary>429 /// Adds a <c><![CDATA[<script>]]></c> tag into the page with the desired url or content430 /// </summary>431 /// <param name="options">add script tag options</param>432 /// <returns>Task which resolves to the added tag when the script's onload fires or when the script content was injected into frame</returns>433 /// <seealso cref="Page.AddScriptTagAsync(AddTagOptions)"/>434 /// <seealso cref="Page.AddScriptTagAsync(string)"/>435 public async Task<ElementHandle> AddScriptTag(AddTagOptions options)436 {437 const string addScriptUrl = @"async function addScriptUrl(url, type) {438 const script = document.createElement('script');439 script.src = url;440 if(type)441 script.type = type;442 const promise = new Promise((res, rej) => {443 script.onload = res;444 script.onerror = rej;445 });446 document.head.appendChild(script);447 await promise;448 return script;449 }";450 const string addScriptContent = @"function addScriptContent(content, type = 'text/javascript') {451 const script = document.createElement('script');452 script.type = type;453 script.text = content;454 let error = null;455 script.onerror = e => error = e;456 document.head.appendChild(script);457 if (error)458 throw error;459 return script;460 }";461 async Task<ElementHandle> AddScriptTagPrivate(string script, string urlOrContent, string type)462 {463 var context = await GetExecutionContextAsync().ConfigureAwait(false);464 return (string.IsNullOrEmpty(type)465 ? await context.EvaluateFunctionHandleAsync(script, urlOrContent).ConfigureAwait(false)466 : await context.EvaluateFunctionHandleAsync(script, urlOrContent, type).ConfigureAwait(false)) as ElementHandle;467 }468 if (!string.IsNullOrEmpty(options.Url))469 {470 var url = options.Url;471 try472 {473 return await AddScriptTagPrivate(addScriptUrl, url, options.Type).ConfigureAwait(false);474 }475 catch (PuppeteerException)476 {477 throw new PuppeteerException($"Loading script from {url} failed");478 }479 }480 if (!string.IsNullOrEmpty(options.Path))...
ElementHandle.cs
Source:ElementHandle.cs
...239 /// <param name="selector">A selector to query element for</param>240 /// <returns>Task which resolves to <see cref="ElementHandle"/> pointing to the frame element</returns>241 public async Task<ElementHandle> QuerySelectorAsync(string selector)242 {243 var handle = await ExecutionContext.EvaluateFunctionHandleAsync(244 "(element, selector) => element.querySelector(selector)",245 this, selector).ConfigureAwait(false);246 if (handle is ElementHandle element)247 {248 return element;249 }250 await handle.DisposeAsync().ConfigureAwait(false);251 return null;252 }253 /// <summary>254 /// Runs <c>element.querySelectorAll</c> within the page. If no elements match the selector, the return value resolve to <see cref="Array.Empty{T}"/>.255 /// </summary>256 /// <param name="selector">A selector to query element for</param>257 /// <returns>Task which resolves to ElementHandles pointing to the frame elements</returns>258 public async Task<ElementHandle[]> QuerySelectorAllAsync(string selector)259 {260 var arrayHandle = await ExecutionContext.EvaluateFunctionHandleAsync(261 "(element, selector) => element.querySelectorAll(selector)",262 this, selector).ConfigureAwait(false);263 var properties = await arrayHandle.GetPropertiesAsync().ConfigureAwait(false);264 await arrayHandle.DisposeAsync().ConfigureAwait(false);265 return properties.Values.OfType<ElementHandle>().ToArray();266 }267 /// <summary>268 /// A utility function to be used with <see cref="Extensions.EvaluateFunctionAsync{T}(Task{JSHandle}, string, object[])"/>269 /// </summary>270 /// <param name="selector">A selector to query element for</param>271 /// <returns>Task which resolves to a <see cref="JSHandle"/> of <c>document.querySelectorAll</c> result</returns>272 public Task<JSHandle> QuerySelectorAllHandleAsync(string selector)273 => ExecutionContext.EvaluateFunctionHandleAsync(274 "(element, selector) => Array.from(element.querySelectorAll(selector))", this, selector);275 /// <summary>276 /// Evaluates the XPath expression relative to the elementHandle. If there's no such element, the method will resolve to <c>null</c>.277 /// </summary>278 /// <param name="expression">Expression to evaluate <see href="https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate"/></param>279 /// <returns>Task which resolves to an array of <see cref="ElementHandle"/></returns>280 public async Task<ElementHandle[]> XPathAsync(string expression)281 {282 var arrayHandle = await ExecutionContext.EvaluateFunctionHandleAsync(283 @"(element, expression) => {284 const document = element.ownerDocument || element;285 const iterator = document.evaluate(expression, element, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE);286 const array = [];287 let item;288 while ((item = iterator.iterateNext()))289 array.push(item);290 return array;291 }",292 this, expression293 ).ConfigureAwait(false);294 var properties = await arrayHandle.GetPropertiesAsync().ConfigureAwait(false);295 await arrayHandle.DisposeAsync().ConfigureAwait(false);296 return properties.Values.OfType<ElementHandle>().ToArray();...
EvaluateTests.cs
Source:EvaluateTests.cs
...177 }178 [Fact]179 public async Task ShouldBeAbleToThrowATrickyError()180 {181 var windowHandle = await Page.EvaluateFunctionHandleAsync("() => window");182 PuppeteerException exception = await Assert.ThrowsAsync<MessageException>(() => windowHandle.JsonValueAsync());183 var errorText = exception.Message;184 exception = await Assert.ThrowsAsync<EvaluationFailedException>(() => Page.EvaluateFunctionAsync(@"errorText =>185 {186 throw new Error(errorText);187 }", errorText));188 Assert.Contains(errorText, exception.Message);189 }190 [Theory]191 [InlineData("1 + 5;", 6)] //ShouldAcceptSemiColons192 [InlineData("2 + 5\n// do some math!'", 7)] //ShouldAceptStringComments193 public async Task BasicIntExressionEvaluationTest(string script, object expected)194 {195 var result = await Page.EvaluateExpressionAsync<int>(script);196 Assert.Equal(expected, result);197 }198 [Fact]199 public async Task ShouldAcceptElementHandleAsAnArgument()200 {201 await Page.SetContentAsync("<section>42</section>");202 var element = await Page.QuerySelectorAsync("section");203 var text = await Page.EvaluateFunctionAsync<string>("e => e.textContent", element);204 Assert.Equal("42", text);205 }206 [Fact]207 public async Task ShouldThrowIfUnderlyingElementWasDisposed()208 {209 await Page.SetContentAsync("<section>39</section>");210 var element = await Page.QuerySelectorAsync("section");211 Assert.NotNull(element);212 await element.DisposeAsync();213 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(()214 => Page.EvaluateFunctionAsync<string>("e => e.textContent", element));215 Assert.Contains("JSHandle is disposed", exception.Message);216 }217 [Fact]218 public async Task ShouldThrowIfElementHandlesAreFromOtherFrames()219 {220 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);221 var bodyHandle = await Page.FirstChildFrame().QuerySelectorAsync("body");222 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(()223 => Page.EvaluateFunctionAsync<string>("body => body.innerHTML", bodyHandle));224 Assert.Contains("JSHandles can be evaluated only in the context they were created", exception.Message);225 }226 [Fact]227 public async Task ShouldSimulateAUserGesture()228 => Assert.True(await Page.EvaluateFunctionAsync<bool>(@"() => {229 document.body.appendChild(document.createTextNode('test'));230 document.execCommand('selectAll');231 return document.execCommand('copy'); 232 }"));233 [Fact]234 public async Task ShouldThrowANiceErrorAfterANavigation()235 {236 var executionContext = await Page.MainFrame.GetExecutionContextAsync();237 await Task.WhenAll(238 Page.WaitForNavigationAsync(),239 executionContext.EvaluateFunctionAsync("() => window.location.reload()")240 );241 var ex = await Assert.ThrowsAsync<EvaluationFailedException>(() =>242 {243 return executionContext.EvaluateFunctionAsync("() => null");244 });245 Assert.Contains("navigation", ex.Message);246 }247 [Fact]248 public async Task ShouldNotThrowAnErrorWhenEvaluationDoesANavigation()249 {250 await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html");251 var result = await Page.EvaluateFunctionAsync<int[]>(@"() =>252 {253 window.location = '/empty.html';254 return [42];255 }");256 Assert.Equal(new[] { 42 }, result);257 }258 /// <summary>259 /// Original Name "should transfer 100Mb of data from page to node.js"260 /// </summary>261 [Fact]262 public async Task ShouldTransfer100MbOfDataFromPage()263 {264 var a = await Page.EvaluateFunctionAsync<string>("() => Array(100 * 1024 * 1024 + 1).join('a')");265 Assert.Equal(100 * 1024 * 1024, a.Length);266 }267 [Fact]268 public async Task ShouldThrowErrorWithDetailedInformationOnExceptionInsidePromise()269 {270 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(() =>271 Page.EvaluateFunctionAsync(272 @"() => new Promise(() => {273 throw new Error('Error in promise');274 })"));275 Assert.Contains("Error in promise", exception.Message);276 }277 [Fact]278 public async Task ShouldWorkWithDifferentSerializerSettings()279 {280 var result = await Page.EvaluateFunctionAsync<ComplexObjectTestClass>("() => { return { foo: 'bar' }}");281 Assert.Equal("bar", result.Foo);282 result = (await Page.EvaluateFunctionAsync<JToken>("() => { return { Foo: 'bar' }}"))283 .ToObject<ComplexObjectTestClass>(new JsonSerializerSettings());284 Assert.Equal("bar", result.Foo);285 result = await Page.EvaluateExpressionAsync<ComplexObjectTestClass>("var obj = { foo: 'bar' }; obj;");286 Assert.Equal("bar", result.Foo);287 result = (await Page.EvaluateExpressionAsync<JToken>("var obj = { Foo: 'bar' }; obj;"))288 .ToObject<ComplexObjectTestClass>(new JsonSerializerSettings());289 Assert.Equal("bar", result.Foo);290 }291 [Fact]292 public async Task ShouldProperlyIgnoreUndefinedFields()293 {294 var result = await Page.EvaluateFunctionAsync<Dictionary<string, object>>("() => ({a: undefined})");295 Assert.Empty(result);296 }297 [Fact]298 public async Task ShouldProperlySerializeNullFields()299 {300 var result = await Page.EvaluateFunctionAsync<Dictionary<string, object>>("() => ({a: null})");301 Assert.True(result.ContainsKey("a"));302 Assert.Null(result["a"]);303 }304 [Fact]305 public async Task ShouldAcceptObjectHandleAsAnArgument()306 {307 var navigatorHandle = await Page.EvaluateExpressionHandleAsync("navigator");308 var text = await Page.EvaluateFunctionAsync<string>("e => e.userAgent", navigatorHandle);309 Assert.Contains("Mozilla", text);310 }311 [Fact]312 public async Task ShouldAcceptObjectHandleToPrimitiveTypes()313 {314 var aHandle = await Page.EvaluateExpressionHandleAsync("5");315 var isFive = await Page.EvaluateFunctionAsync<bool>("e => Object.is(e, 5)", aHandle);316 Assert.True(isFive);317 }318 [Fact]319 public async Task ShouldWarnOnNestedObjectHandles()320 {321 var handle = await Page.EvaluateFunctionHandleAsync("() => document.body");322 var elementHandle = handle as ElementHandle;323 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(()324 => Page.EvaluateFunctionHandleAsync(325 "opts => opts.elem.querySelector('p')",326 new { elem = handle }));327 Assert.Contains("Are you passing a nested JSHandle?", exception.Message);328 //Check with ElementHandle329 exception = await Assert.ThrowsAsync<EvaluationFailedException>(()330 => Page.EvaluateFunctionHandleAsync(331 "opts => opts.elem.querySelector('p')",332 new { elem = elementHandle }));333 Assert.Contains("Are you passing a nested JSHandle?", exception.Message);334 }335 [Fact]336 public async Task ShouldWorkWithoutGenerics()337 {338 Assert.NotNull(await Page.EvaluateExpressionAsync("var obj = {}; obj;"));339 Assert.NotNull(await Page.EvaluateExpressionAsync("[]"));340 Assert.NotNull(await Page.EvaluateExpressionAsync("''"));341 var objectPopulated = await Page.EvaluateExpressionAsync("var obj = {a:1}; obj;");342 Assert.NotNull(objectPopulated);343 Assert.Equal(1, objectPopulated["a"]);344 var arrayPopulated = await Page.EvaluateExpressionAsync("[1]");...
DOMWorld.cs
Source:DOMWorld.cs
...60 {61 var context = await GetExecutionContextAsync().ConfigureAwait(false);62 return await context.EvaluateExpressionHandleAsync(script).ConfigureAwait(false);63 }64 internal async Task<JSHandle> EvaluateFunctionHandleAsync(string script, params object[] args)65 {66 var context = await GetExecutionContextAsync().ConfigureAwait(false);67 return await context.EvaluateFunctionHandleAsync(script, args).ConfigureAwait(false);68 }69 internal async Task<T> EvaluateExpressionAsync<T>(string script)70 {71 var context = await GetExecutionContextAsync().ConfigureAwait(false);72 return await context.EvaluateExpressionAsync<T>(script).ConfigureAwait(false);73 }74 internal async Task<JToken> EvaluateExpressionAsync(string script)75 {76 var context = await GetExecutionContextAsync().ConfigureAwait(false);77 return await context.EvaluateExpressionAsync(script).ConfigureAwait(false);78 }79 internal async Task<T> EvaluateFunctionAsync<T>(string script, params object[] args)80 {81 var context = await GetExecutionContextAsync().ConfigureAwait(false);82 return await context.EvaluateFunctionAsync<T>(script, args).ConfigureAwait(false);83 }84 internal async Task<JToken> EvaluateFunctionAsync(string script, params object[] args)85 {86 var context = await GetExecutionContextAsync().ConfigureAwait(false);87 return await context.EvaluateFunctionAsync(script, args).ConfigureAwait(false);88 }89 internal Task<string> GetContentAsync() => EvaluateFunctionAsync<string>(@"() => {90 let retVal = '';91 if (document.doctype)92 retVal = new XMLSerializer().serializeToString(document.doctype);93 if (document.documentElement)94 retVal += document.documentElement.outerHTML;95 return retVal;96 }");97 internal async Task SetContentAsync(string html, NavigationOptions options = null)98 {99 var waitUntil = options?.WaitUntil ?? new[] { WaitUntilNavigation.Load };100 var timeout = options?.Timeout ?? _timeoutSettings.NavigationTimeout;101 // We rely upon the fact that document.open() will reset frame lifecycle with "init"102 // lifecycle event. @see https://crrev.com/608658103 await EvaluateFunctionAsync(@"html => {104 document.open();105 document.write(html);106 document.close();107 }", html).ConfigureAwait(false);108 using (var watcher = new LifecycleWatcher(_frameManager, Frame, waitUntil, timeout))109 {110 var watcherTask = await Task.WhenAny(111 watcher.TimeoutOrTerminationTask,112 watcher.LifecycleTask).ConfigureAwait(false);113 await watcherTask.ConfigureAwait(false);114 }115 }116 internal async Task<ElementHandle> AddScriptTagAsync(AddTagOptions options)117 {118 const string addScriptUrl = @"async function addScriptUrl(url, type) {119 const script = document.createElement('script');120 script.src = url;121 if(type)122 script.type = type;123 const promise = new Promise((res, rej) => {124 script.onload = res;125 script.onerror = rej;126 });127 document.head.appendChild(script);128 await promise;129 return script;130 }";131 const string addScriptContent = @"function addScriptContent(content, type = 'text/javascript') {132 const script = document.createElement('script');133 script.type = type;134 script.text = content;135 let error = null;136 script.onerror = e => error = e;137 document.head.appendChild(script);138 if (error)139 throw error;140 return script;141 }";142 async Task<ElementHandle> AddScriptTagPrivate(string script, string urlOrContent, string type)143 {144 var context = await GetExecutionContextAsync().ConfigureAwait(false);145 return (string.IsNullOrEmpty(type)146 ? await context.EvaluateFunctionHandleAsync(script, urlOrContent).ConfigureAwait(false)147 : await context.EvaluateFunctionHandleAsync(script, urlOrContent, type).ConfigureAwait(false)) as ElementHandle;148 }149 if (!string.IsNullOrEmpty(options.Url))150 {151 var url = options.Url;152 try153 {154 return await AddScriptTagPrivate(addScriptUrl, url, options.Type).ConfigureAwait(false);155 }156 catch (PuppeteerException)157 {158 throw new PuppeteerException($"Loading script from {url} failed");159 }160 }161 if (!string.IsNullOrEmpty(options.Path))162 {163 var contents = await AsyncFileHelper.ReadAllText(options.Path).ConfigureAwait(false);164 contents += "//# sourceURL=" + options.Path.Replace("\n", string.Empty);165 return await AddScriptTagPrivate(addScriptContent, contents, options.Type).ConfigureAwait(false);166 }167 if (!string.IsNullOrEmpty(options.Content))168 {169 return await AddScriptTagPrivate(addScriptContent, options.Content, options.Type).ConfigureAwait(false);170 }171 throw new ArgumentException("Provide options with a `Url`, `Path` or `Content` property");172 }173 internal async Task<ElementHandle> AddStyleTagAsync(AddTagOptions options)174 {175 const string addStyleUrl = @"async function addStyleUrl(url) {176 const link = document.createElement('link');177 link.rel = 'stylesheet';178 link.href = url;179 const promise = new Promise((res, rej) => {180 link.onload = res;181 link.onerror = rej;182 });183 document.head.appendChild(link);184 await promise;185 return link;186 }";187 const string addStyleContent = @"async function addStyleContent(content) {188 const style = document.createElement('style');189 style.type = 'text/css';190 style.appendChild(document.createTextNode(content));191 const promise = new Promise((res, rej) => {192 style.onload = res;193 style.onerror = rej;194 });195 document.head.appendChild(style);196 await promise;197 return style;198 }";199 if (!string.IsNullOrEmpty(options.Url))200 {201 var url = options.Url;202 try203 {204 var context = await GetExecutionContextAsync().ConfigureAwait(false);205 return (await context.EvaluateFunctionHandleAsync(addStyleUrl, url).ConfigureAwait(false)) as ElementHandle;206 }207 catch (PuppeteerException)208 {209 throw new PuppeteerException($"Loading style from {url} failed");210 }211 }212 if (!string.IsNullOrEmpty(options.Path))213 {214 var contents = await AsyncFileHelper.ReadAllText(options.Path).ConfigureAwait(false);215 contents += "//# sourceURL=" + options.Path.Replace("\n", string.Empty);216 var context = await GetExecutionContextAsync().ConfigureAwait(false);217 return (await context.EvaluateFunctionHandleAsync(addStyleContent, contents).ConfigureAwait(false)) as ElementHandle;218 }219 if (!string.IsNullOrEmpty(options.Content))220 {221 var context = await GetExecutionContextAsync().ConfigureAwait(false);222 return (await context.EvaluateFunctionHandleAsync(addStyleContent, options.Content).ConfigureAwait(false)) as ElementHandle;223 }224 throw new ArgumentException("Provide options with a `Url`, `Path` or `Content` property");225 }226 internal Task<ElementHandle> WaitForSelectorAsync(string selector, WaitForSelectorOptions options = null)227 => WaitForSelectorOrXPathAsync(selector, false, options);228 internal Task<ElementHandle> WaitForXPathAsync(string xpath, WaitForSelectorOptions options = null)229 => WaitForSelectorOrXPathAsync(xpath, true, options);230 internal Task<JSHandle> WaitForFunctionAsync(string script, WaitForFunctionOptions options, params object[] args)231 => new WaitTask(232 this,233 script,234 false,235 "function",236 options.Polling,...
ExecutionContext.cs
Source:ExecutionContext.cs
...69 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.70 /// <see cref="JSHandle"/> instances can be passed as arguments71 /// </remarks>72 /// <seealso cref="EvaluateExpressionAsync{T}(string)"/>73 /// <seealso cref="EvaluateFunctionHandleAsync(string, object[])"/>74 /// <returns>Task which resolves to script return value</returns>75 public Task<JToken> EvaluateFunctionAsync(string script, params object[] args)76 => EvaluateAsync<JToken>(EvaluateFunctionHandleAsync(script, args));77 /// <summary>78 /// Executes a function in browser context79 /// </summary>80 /// <typeparam name="T">The type to deserialize the result to</typeparam>81 /// <param name="script">Script to be evaluated in browser context</param>82 /// <param name="args">Arguments to pass to script</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 /// <see cref="JSHandle"/> instances can be passed as arguments86 /// </remarks>87 /// <seealso cref="EvaluateExpressionAsync{T}(string)"/>88 /// <seealso cref="EvaluateFunctionHandleAsync(string, object[])"/>89 /// <returns>Task which resolves to script return value</returns>90 public Task<T> EvaluateFunctionAsync<T>(string script, params object[] args)91 => EvaluateAsync<T>(EvaluateFunctionHandleAsync(script, args));92 /// <summary>93 /// The method iterates JavaScript heap and finds all the objects with the given prototype.94 /// </summary>95 /// <returns>A task which resolves to a handle to an array of objects with this prototype.</returns>96 /// <param name="prototypeHandle">A handle to the object prototype.</param>97 public async Task<JSHandle> QueryObjectsAsync(JSHandle prototypeHandle)98 {99 if (prototypeHandle.Disposed)100 {101 throw new PuppeteerException("Prototype JSHandle is disposed!");102 }103 if (!((JObject)prototypeHandle.RemoteObject).TryGetValue(MessageKeys.ObjectId, out var objectId))104 {105 throw new PuppeteerException("Prototype JSHandle must not be referencing primitive value");106 }107 var response = await _client.SendAsync("Runtime.queryObjects", new Dictionary<string, object>108 {109 {"prototypeObjectId", objectId.ToString()}110 }).ConfigureAwait(false);111 return CreateJSHandle(response[MessageKeys.Objects]);112 }113 internal async Task<JSHandle> EvaluateExpressionHandleAsync(string script)114 {115 if (string.IsNullOrEmpty(script))116 {117 return null;118 }119 try120 {121 return await EvaluateHandleAsync("Runtime.evaluate", new Dictionary<string, object>122 {123 ["expression"] = _sourceUrlRegex.IsMatch(script) ? script : $"{script}\n{EvaluationScriptSuffix}",124 ["contextId"] = _contextId,125 ["returnByValue"] = false,126 ["awaitPromise"] = true,127 ["userGesture"] = true128 }).ConfigureAwait(false);129 }130 catch (Exception ex)131 {132 throw new EvaluationFailedException(ex.Message, ex);133 }134 }135 internal async Task<JSHandle> EvaluateFunctionHandleAsync(string script, params object[] args)136 {137 if (string.IsNullOrEmpty(script))138 {139 return null;140 }141 try142 {143 return await EvaluateHandleAsync("Runtime.callFunctionOn", new Dictionary<string, object>144 {145 ["functionDeclaration"] = $"{script}\n{EvaluationScriptSuffix}\n",146 [MessageKeys.ExecutionContextId] = _contextId,147 ["arguments"] = args.Select(FormatArgument),148 ["returnByValue"] = false,149 ["awaitPromise"] = true,...
PageExtensions.cs
Source:PageExtensions.cs
...17 /// <returns>Task which resolves to <see cref="ElementHandle"/> pointing to the frame element</returns>18 /// <seealso href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp"/>19 public static async Task<ElementHandle> QuerySelectorWithContentAsync(this Page page, string selector, string regex, string flags = "")20 {21 return await page.GuardFromNull().EvaluateFunctionHandleAsync(22 @"(selector, regex, flags) => {23 var elements = document.querySelectorAll(selector);24 return Array.prototype.find.call(elements, function(element) {25 return RegExp(regex, flags).test(element.textContent);26 });27 }", selector, regex, flags).ConfigureAwait(false) as ElementHandle;28 }29 /// <summary>30 /// The method runs <c>document.querySelectorAll</c> within the page and then tests a <c>RegExp</c> against the elements <c>textContent</c>. All element matches are returned. If no element matches the selector and regular expression, the return value resolve to <see cref="System.Array.Empty{T}"/>.31 /// </summary>32 /// <param name="page">A <see cref="Page"/> to query</param>33 /// <param name="selector">A selector to query page for</param>34 /// <param name="regex">A regular expression to test against <c>element.textContent</c></param>35 /// <param name="flags">A set of flags for the regular expression</param>36 /// <returns>Task which resolves to ElementHandles pointing to the frame elements</returns>37 /// <seealso href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp"/>38 public static async Task<ElementHandle[]> QuerySelectorAllWithContentAsync(this Page page, string selector, string regex, string flags = "")39 {40 var arrayHandle = await page.GuardFromNull().EvaluateFunctionHandleAsync(41 @"(selector, regex, flags) => {42 var elements = document.querySelectorAll(selector);43 return Array.prototype.filter.call(elements, function(element) {44 return RegExp(regex, flags).test(element.textContent);45 });46 }", selector, regex, flags).ConfigureAwait(false);47 var properties = await arrayHandle.GetPropertiesAsync().ConfigureAwait(false);48 await arrayHandle.DisposeAsync().ConfigureAwait(false);49 return properties.Values.OfType<ElementHandle>().ToArray();50 }51 /// <summary>52 /// Indicates whether the page has the specified content or not.53 /// </summary>54 /// <param name="page">A <see cref="Page"/></param>...
BoxModelTests.cs
Source:BoxModelTests.cs
...27 top: 2px;28 `;");29 // Step 2: Add div and position it absolutely inside frame.30 var frame = Page.FirstChildFrame();31 var divHandle = (ElementHandle)await frame.EvaluateFunctionHandleAsync(@"() => {32 const div = document.createElement('div');33 document.body.appendChild(div);34 div.style = `35 box-sizing: border-box;36 position: absolute;37 border-left: 1px solid black;38 padding-left: 2px;39 margin-left: 3px;40 left: 4px;41 top: 5px;42 width: 6px;43 height: 7px;44 `;45 return div;...
FrameUtils.cs
Source:FrameUtils.cs
...6 public static class FrameUtils7 {8 public static async Task<Frame> AttachFrameAsync(Page page, string frameId, string url)9 {10 var handle = await page.EvaluateFunctionHandleAsync(@" async (frameId, url) => {11 const frame = document.createElement('iframe');12 frame.src = url;13 frame.id = frameId;14 document.body.appendChild(frame);15 await new Promise(x => frame.onload = x);16 return frame17 }", frameId, url) as ElementHandle;18 return await handle.ContentFrameAsync();19 }20 public static async Task DetachFrameAsync(Page page, string frameId)21 {22 await page.EvaluateFunctionAsync(@"function detachFrame(frameId) {23 const frame = document.getElementById(frameId);24 frame.remove();...
EvaluateFunctionHandleAsync
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 result = await page.EvaluateFunctionHandleAsync("function() { return 1; }");13 Console.WriteLine(result);14 await browser.CloseAsync();15 }16 }17}18Your name to display (optional):19Your name to display (optional):20using System;21using System.Threading.Tasks;22using PuppeteerSharp;23{24 {25 static async Task Main(string[] args)26 {27 var browser = await Puppeteer.LaunchAsync(new LaunchOptions28 {29 });30 var page = await browser.NewPageAsync();31 var result = await page.EvaluateFunctionHandleAsync("function() { return 1; }");32 Console.WriteLine(result);33 await browser.CloseAsync();34 }35 }36}37Your name to display (optional):
EvaluateFunctionHandleAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))10 {11 var page = await browser.NewPageAsync();12 await page.EvaluateFunctionHandleAsync("() => document.querySelector('input').value = 'PuppeteerSharp'");13 Console.ReadLine();14 }15 }16 }17}18using System;19using System.Threading.Tasks;20using PuppeteerSharp;21{22 {23 static async Task Main(string[] args)24 {25 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);26 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))27 {28 var page = await browser.NewPageAsync();29 await page.EvaluateFunctionHandleAsync("() => document.querySelector('input').value = 'PuppeteerSharp'");30 Console.ReadLine();31 }32 }33 }34}35using System;36using System.Threading.Tasks;37using PuppeteerSharp;38{39 {40 static async Task Main(string[] args)41 {42 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);43 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))44 {45 var page = await browser.NewPageAsync();46 var frame = page.MainFrame;47 await frame.EvaluateFunctionHandleAsync("() => document.querySelector('input').value = 'PuppeteerSharp'");48 Console.ReadLine();49 }50 }51 }52}53using System;54using System.Threading.Tasks;55using PuppeteerSharp;56{
EvaluateFunctionHandleAsync
Using AI Code Generation
1using System;2using System.IO;3using System.Threading.Tasks;4using PuppeteerSharp;5{6 {7 static async Task Main(string[] args)8 {9 var option = new LaunchOptions { Headless = true };10 var browser = await Puppeteer.LaunchAsync(option);11 var page = await browser.NewPageAsync();12 await page.EvaluateFunctionHandleAsync("() => document.body.style.backgroundColor = 'red'");13 await page.ScreenshotAsync("1.png");14 Console.WriteLine("Screenshot saved to 1.png");15 await browser.CloseAsync();16 }17 }18}
EvaluateFunctionHandleAsync
Using AI Code Generation
1var puppeteer = require("puppeteer");2var fs = require("fs");3var path = require("path");4var pathToExtension = path.join(__dirname, "extension");5var extensionFiles = fs.readdirSync(pathToExtension);6var extension = {};7extensionFiles.forEach(function (file) {8 var filePath = path.join(pathToExtension, file);9 var stat = fs.statSync(filePath);10 if (stat.isFile()) {11 extension[file] = fs.readFileSync(filePath, "utf8");12 }13});14var browser = await puppeteer.launch({15});16var page = await browser.newPage();17await page.goto(url);18await page.waitFor(5000);19await page.evaluate(() => {20 var element = document.querySelector("#hplogo");21 element.style.border = "10px solid red";22});23var frame = page.mainFrame();24var handle = await frame.evaluateHandle(() => {25 var element = document.querySelector("#hplogo");26 return element;27});28var result = await frame.evaluateHandle(29 (element) => {30 return element.style.border;31 },32);33var border = await result.jsonValue();34console.log(border);35await browser.close();
EvaluateFunctionHandleAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args)7 {8 MainAsync().GetAwaiter().GetResult();9 }10 static async Task MainAsync()11 {12 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))13 {14 var page = await browser.NewPageAsync();15 var title = await page.EvaluateFunctionHandleAsync(@"() => {16 return document.title;17 }");18 Console.WriteLine(title);19 }20 }21 }22}23using System;24using System.Threading.Tasks;25using PuppeteerSharp;26{27 {28 static void Main(string[] args)29 {30 MainAsync().GetAwaiter().GetResult();31 }32 static async Task MainAsync()33 {34 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))35 {36 var page = await browser.NewPageAsync();37 var title = await page.EvaluateFunctionHandleAsync(@"() => {38 return document.title;39 }");40 var value = await title.JsonValueAsync();41 Console.WriteLine(value);42 }43 }44 }45}46using System;47using System.Threading.Tasks;48using PuppeteerSharp;49{50 {51 static void Main(string[] args)52 {53 MainAsync().GetAwaiter().GetResult();54 }55 static async Task MainAsync()56 {57 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions
EvaluateFunctionHandleAsync
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 static async Task MainAsync()11 {12 var browser = await Puppeteer.LaunchAsync(new LaunchOptions13 {14 });15 var page = await browser.NewPageAsync();16 var elementHandle = await page.QuerySelectorAsync("input[name=search]");17 var searchValue = await page.EvaluateFunctionHandleAsync<string>(@"(element) => {18 element.value = 'Puppeteer';19 return element.value;20 }", elementHandle);21 Console.WriteLine(searchValue);22 await browser.CloseAsync();23 }24 }25}
EvaluateFunctionHandleAsync
Using AI Code Generation
1using PuppeteerSharp;2{3 {4 static void Main(string[] args)5 {6 EvaluateFunctionHandleAsync().Wait();7 }8 private static async Task EvaluateFunctionHandleAsync()9 {10 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions11 {12 Args = new string[] { "--no-sandbox" }13 }))14 {15 var page = await browser.NewPageAsync();16 await page.SetViewportAsync(new ViewPortOptions { Width = 1366, Height = 768 });17 var functionHandle = await page.EvaluateFunctionHandleAsync("() => { return document.body; }");18 var value = await functionHandle.JsonValueAsync();19 Console.WriteLine(value);20 }21 }22 }23}
EvaluateFunctionHandleAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))10 using (var page = await browser.NewPageAsync())11 {12 var title = await page.EvaluateFunctionHandleAsync("() => document.title");13 Console.WriteLine(await page.EvaluateFunctionAsync<string>("x => x", title));14 }15 }16 }17}18using System;19using System.Threading.Tasks;20using PuppeteerSharp;21{22 {23 static async Task Main(string[] args)24 {25 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);26 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))27 using (var page = await browser.NewPageAsync())28 {29 var title = await page.EvaluateFunctionHandleAsync("() => document.title");30 var element = await page.EvaluateFunctionHandleAsync("() => document.body");31 Console.WriteLine(await page.EvaluateFunctionAsync<string>("(x, y) => x === y, title, element"));32 }33 }34 }35}
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!!