Best Puppeteer-sharp code snippet using PuppeteerSharp.Worker.EvaluateFunctionAsync
Page.cs
Source:Page.cs
...315 }316 #endregion317 #region Public Methods318 /// <summary>319 /// A utility function to be used with <see cref="Extensions.EvaluateFunctionAsync{T}(Task{JSHandle}, string, object[])"/>320 /// </summary>321 /// <param name="selector">A selector to query page for</param>322 /// <returns>Task which resolves to a <see cref="JSHandle"/> of <c>document.querySelectorAll</c> result</returns>323 public Task<JSHandle> QuerySelectorAllHandleAsync(string selector)324 => EvaluateFunctionHandleAsync("selector => Array.from(document.querySelectorAll(selector))", selector);325 /// <summary>326 /// Executes a script in browser context327 /// </summary>328 /// <param name="script">Script to be evaluated in browser context</param>329 /// <remarks>330 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.331 /// </remarks>332 /// <returns>Task which resolves to script return value</returns>333 public async Task<JSHandle> EvaluateExpressionHandleAsync(string script)334 {335 var context = await MainFrame.GetExecutionContextAsync().ConfigureAwait(false);336 return await context.EvaluateExpressionHandleAsync(script).ConfigureAwait(false);337 }338 /// <summary>339 /// Executes a script in browser context340 /// </summary>341 /// <param name="pageFunction">Script to be evaluated in browser context</param>342 /// <param name="args">Function arguments</param>343 /// <remarks>344 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.345 /// <see cref="JSHandle"/> instances can be passed as arguments346 /// </remarks>347 /// <returns>Task which resolves to script return value</returns>348 public async Task<JSHandle> EvaluateFunctionHandleAsync(string pageFunction, params object[] args)349 {350 var context = await MainFrame.GetExecutionContextAsync().ConfigureAwait(false);351 return await context.EvaluateFunctionHandleAsync(pageFunction, args).ConfigureAwait(false);352 }353 /// <summary>354 /// Activating request interception enables <see cref="Request.AbortAsync(RequestAbortErrorCode)">request.AbortAsync</see>, 355 /// <see cref="Request.ContinueAsync(Payload)">request.ContinueAsync</see> and <see cref="Request.RespondAsync(ResponseData)">request.RespondAsync</see> methods.356 /// </summary>357 /// <returns>The request interception task.</returns>358 /// <param name="value">Whether to enable request interception..</param>359 public Task SetRequestInterceptionAsync(bool value)360 => FrameManager.NetworkManager.SetRequestInterceptionAsync(value);361 /// <summary>362 /// Set offline mode for the page.363 /// </summary>364 /// <returns>Result task</returns>365 /// <param name="value">When <c>true</c> enables offline mode for the page.</param>366 public Task SetOfflineModeAsync(bool value) => FrameManager.NetworkManager.SetOfflineModeAsync(value);367 /// <summary>368 /// Adds a <c><![CDATA[<script>]]></c> tag into the page with the desired url or content369 /// </summary>370 /// <param name="options">add script tag options</param>371 /// <remarks>372 /// Shortcut for <c>page.MainFrame.AddScriptTagAsync(options)</c>373 /// </remarks>374 /// <returns>Task which resolves to the added tag when the script's onload fires or when the script content was injected into frame</returns>375 /// <seealso cref="Frame.AddScriptTagAsync(AddTagOptions)"/>376 public Task<ElementHandle> AddScriptTagAsync(AddTagOptions options) => MainFrame.AddScriptTagAsync(options);377 /// <summary>378 /// Adds a <c><![CDATA[<script>]]></c> tag into the page with the desired url or content379 /// </summary>380 /// <param name="url">script url</param>381 /// <remarks>382 /// Shortcut for <c>page.MainFrame.AddScriptTagAsync(new AddTagOptions { Url = url })</c>383 /// </remarks>384 /// <returns>Task which resolves to the added tag when the script's onload fires or when the script content was injected into frame</returns>385 public Task<ElementHandle> AddScriptTagAsync(string url) => AddScriptTagAsync(new AddTagOptions { Url = url });386 /// <summary>387 /// 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 content388 /// </summary>389 /// <param name="options">add style tag options</param>390 /// <remarks>391 /// Shortcut for <c>page.MainFrame.AddStyleTagAsync(options)</c>392 /// </remarks>393 /// <returns>Task which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame</returns>394 /// <seealso cref="Frame.AddStyleTag(AddTagOptions)"/>395 public Task<ElementHandle> AddStyleTagAsync(AddTagOptions options) => MainFrame.AddStyleTagAsync(options);396 /// <summary>397 /// 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 content398 /// </summary>399 /// <param name="url">stylesheel url</param>400 /// <remarks>401 /// Shortcut for <c>page.MainFrame.AddStyleTagAsync(new AddTagOptions { Url = url })</c>402 /// </remarks>403 /// <returns>Task which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame</returns>404 public Task<ElementHandle> AddStyleTagAsync(string url) => AddStyleTagAsync(new AddTagOptions { Url = url });405 /// <summary>406 /// Adds a function called <c>name</c> on the page's <c>window</c> object.407 /// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves when <paramref name="puppeteerFunction"/> completes.408 /// </summary>409 /// <param name="name">Name of the function on the window object</param>410 /// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>411 /// <remarks>412 /// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.413 /// Functions installed via <see cref="ExposeFunctionAsync(string, Action)"/> survive navigations414 /// </remarks>415 /// <returns>Task</returns>416 public Task ExposeFunctionAsync(string name, Action puppeteerFunction)417 => ExposeFunctionAsync(name, (Delegate)puppeteerFunction);418 /// <summary>419 /// Adds a function called <c>name</c> on the page's <c>window</c> object.420 /// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves to the return value of <paramref name="puppeteerFunction"/>.421 /// </summary>422 /// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>423 /// <param name="name">Name of the function on the window object</param>424 /// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>425 /// <remarks>426 /// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.427 /// Functions installed via <see cref="ExposeFunctionAsync{TResult}(string, Func{TResult})"/> survive navigations428 /// </remarks>429 /// <returns>Task</returns>430 public Task ExposeFunctionAsync<TResult>(string name, Func<TResult> puppeteerFunction)431 => ExposeFunctionAsync(name, (Delegate)puppeteerFunction);432 /// <summary>433 /// Adds a function called <c>name</c> on the page's <c>window</c> object.434 /// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves to the return value of <paramref name="puppeteerFunction"/>.435 /// </summary>436 /// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>437 /// <typeparam name="T">The parameter of <paramref name="puppeteerFunction"/></typeparam>438 /// <param name="name">Name of the function on the window object</param>439 /// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>440 /// <remarks>441 /// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.442 /// Functions installed via <see cref="ExposeFunctionAsync{T, TResult}(string, Func{T, TResult})"/> survive navigations443 /// </remarks>444 /// <returns>Task</returns>445 public Task ExposeFunctionAsync<T, TResult>(string name, Func<T, TResult> puppeteerFunction)446 => ExposeFunctionAsync(name, (Delegate)puppeteerFunction);447 /// <summary>448 /// Adds a function called <c>name</c> on the page's <c>window</c> object.449 /// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves to the return value of <paramref name="puppeteerFunction"/>.450 /// </summary>451 /// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>452 /// <typeparam name="T1">The first parameter of <paramref name="puppeteerFunction"/></typeparam>453 /// <typeparam name="T2">The second parameter of <paramref name="puppeteerFunction"/></typeparam>454 /// <param name="name">Name of the function on the window object</param>455 /// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>456 /// <remarks>457 /// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.458 /// Functions installed via <see cref="ExposeFunctionAsync{T1, T2, TResult}(string, Func{T1, T2, TResult})"/> survive navigations459 /// </remarks>460 /// <returns>Task</returns>461 public Task ExposeFunctionAsync<T1, T2, TResult>(string name, Func<T1, T2, TResult> puppeteerFunction)462 => ExposeFunctionAsync(name, (Delegate)puppeteerFunction);463 /// <summary>464 /// Adds a function called <c>name</c> on the page's <c>window</c> object.465 /// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves to the return value of <paramref name="puppeteerFunction"/>.466 /// </summary>467 /// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>468 /// <typeparam name="T1">The first parameter of <paramref name="puppeteerFunction"/></typeparam>469 /// <typeparam name="T2">The second parameter of <paramref name="puppeteerFunction"/></typeparam>470 /// <typeparam name="T3">The third parameter of <paramref name="puppeteerFunction"/></typeparam>471 /// <param name="name">Name of the function on the window object</param>472 /// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>473 /// <remarks>474 /// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.475 /// Functions installed via <see cref="ExposeFunctionAsync{T1, T2, T3, TResult}(string, Func{T1, T2, T3, TResult})"/> survive navigations476 /// </remarks>477 /// <returns>Task</returns>478 public Task ExposeFunctionAsync<T1, T2, T3, TResult>(string name, Func<T1, T2, T3, TResult> puppeteerFunction)479 => ExposeFunctionAsync(name, (Delegate)puppeteerFunction);480 /// <summary>481 /// Adds a function called <c>name</c> on the page's <c>window</c> object.482 /// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves to the return value of <paramref name="puppeteerFunction"/>.483 /// </summary>484 /// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>485 /// <typeparam name="T1">The first parameter of <paramref name="puppeteerFunction"/></typeparam>486 /// <typeparam name="T2">The second parameter of <paramref name="puppeteerFunction"/></typeparam>487 /// <typeparam name="T3">The third parameter of <paramref name="puppeteerFunction"/></typeparam>488 /// <typeparam name="T4">The fourth parameter of <paramref name="puppeteerFunction"/></typeparam>489 /// <param name="name">Name of the function on the window object</param>490 /// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>491 /// <remarks>492 /// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.493 /// Functions installed via <see cref="ExposeFunctionAsync{T1, T2, T3, T4, TResult}(string, Func{T1, T2, T3, T4, TResult})"/> survive navigations494 /// </remarks>495 /// <returns>Task</returns>496 public Task ExposeFunctionAsync<T1, T2, T3, T4, TResult>(string name, Func<T1, T2, T3, T4, TResult> puppeteerFunction)497 => ExposeFunctionAsync(name, (Delegate)puppeteerFunction);498 /// <summary>499 /// Gets the full HTML contents of the page, including the doctype.500 /// </summary>501 /// <returns>Task which resolves to the HTML content.</returns>502 /// <seealso cref="Frame.GetContentAsync"/>503 public Task<string> GetContentAsync() => FrameManager.MainFrame.GetContentAsync();504 /// <summary>505 /// Sets the HTML markup to the page506 /// </summary>507 /// <param name="html">HTML markup to assign to the page.</param>508 /// <param name="options">The navigations options</param>509 /// <returns>Task.</returns>510 /// <seealso cref="Frame.SetContentAsync(string, NavigationOptions)"/>511 public Task SetContentAsync(string html, NavigationOptions options = null) => FrameManager.MainFrame.SetContentAsync(html, options);512 /// <summary>513 /// Navigates to an url514 /// </summary>515 /// <remarks>516 /// <see cref="GoToAsync(string, int?, WaitUntilNavigation[])"/> will throw an error if:517 /// - there's an SSL error (e.g. in case of self-signed certificates).518 /// - target URL is invalid.519 /// - the `timeout` is exceeded during navigation.520 /// - the remote server does not respond or is unreachable.521 /// - the main resource failed to load.522 /// 523 /// <see cref="GoToAsync(string, int?, WaitUntilNavigation[])"/> will not throw an error when any valid HTTP status code is returned by the remote server, 524 /// including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling <see cref="Response.Status"/>525 /// 526 /// > **NOTE** <see cref="GoToAsync(string, int?, WaitUntilNavigation[])"/> either throws an error or returns a main resource response. 527 /// The only exceptions are navigation to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.528 /// 529 /// > **NOTE** Headless mode doesn't support navigation to a PDF document. See the <see fref="https://bugs.chromium.org/p/chromium/issues/detail?id=761295">upstream issue</see>.530 /// 531 /// Shortcut for <seealso cref="Frame.GoToAsync(string, int?, WaitUntilNavigation[])"/>532 /// </remarks>533 /// <param name="url">URL to navigate page to. The url should include scheme, e.g. https://.</param>534 /// <param name="options">Navigation parameters.</param>535 /// <returns>Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.</returns>536 /// <seealso cref="GoToAsync(string, int?, WaitUntilNavigation[])"/>537 public Task<Response> GoToAsync(string url, NavigationOptions options) => FrameManager.MainFrame.GoToAsync(url, options);538 /// <summary>539 /// Navigates to an url540 /// </summary>541 /// <param name="url">URL to navigate page to. The url should include scheme, e.g. https://.</param>542 /// <param name="timeout">Maximum navigation time in milliseconds, defaults to 30 seconds, pass <c>0</c> to disable timeout. </param>543 /// <param name="waitUntil">When to consider navigation succeeded, defaults to <see cref="WaitUntilNavigation.Load"/>. Given an array of <see cref="WaitUntilNavigation"/>, navigation is considered to be successful after all events have been fired</param>544 /// <returns>Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect</returns>545 /// <seealso cref="GoToAsync(string, NavigationOptions)"/>546 public Task<Response> GoToAsync(string url, int? timeout = null, WaitUntilNavigation[] waitUntil = null)547 => GoToAsync(url, new NavigationOptions { Timeout = timeout, WaitUntil = waitUntil });548 /// <summary>549 /// Navigates to an url550 /// </summary>551 /// <param name="url">URL to navigate page to. The url should include scheme, e.g. https://.</param>552 /// <param name="waitUntil">When to consider navigation succeeded.</param>553 /// <returns>Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect</returns>554 /// <seealso cref="GoToAsync(string, NavigationOptions)"/>555 public Task<Response> GoToAsync(string url, WaitUntilNavigation waitUntil)556 => GoToAsync(url, new NavigationOptions { WaitUntil = new[] { waitUntil } });557 /// <summary>558 /// generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaAsync(MediaType)"/> with <see cref="MediaType.Screen"/>559 /// </summary>560 /// <param name="file">The file path to save the PDF to. paths are resolved using <see cref="Path.GetFullPath(string)"/></param>561 /// <returns></returns>562 /// <remarks>563 /// Generating a pdf is currently only supported in Chrome headless564 /// </remarks>565 public Task PdfAsync(string file) => PdfAsync(file, new PdfOptions());566 /// <summary>567 /// generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaAsync(MediaType)"/> with <see cref="MediaType.Screen"/>568 /// </summary>569 /// <param name="file">The file path to save the PDF to. paths are resolved using <see cref="Path.GetFullPath(string)"/></param>570 /// <param name="options">pdf options</param>571 /// <returns></returns>572 /// <remarks>573 /// Generating a pdf is currently only supported in Chrome headless574 /// </remarks>575 public async Task PdfAsync(string file, PdfOptions options)576 => await PdfInternalAsync(file, options).ConfigureAwait(false);577 /// <summary>578 /// generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaAsync(MediaType)"/> with <see cref="MediaType.Screen"/>579 /// </summary>580 /// <returns>Task which resolves to a <see cref="Stream"/> containing the PDF data.</returns>581 /// <remarks>582 /// Generating a pdf is currently only supported in Chrome headless583 /// </remarks>584 public Task<Stream> PdfStreamAsync() => PdfStreamAsync(new PdfOptions());585 /// <summary>586 /// Generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaAsync(MediaType)"/> with <see cref="MediaType.Screen"/>587 /// </summary>588 /// <param name="options">pdf options</param>589 /// <returns>Task which resolves to a <see cref="Stream"/> containing the PDF data.</returns>590 /// <remarks>591 /// Generating a pdf is currently only supported in Chrome headless592 /// </remarks>593 public async Task<Stream> PdfStreamAsync(PdfOptions options)594 => new MemoryStream(await PdfDataAsync(options).ConfigureAwait(false));595 /// <summary>596 /// Generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaAsync(MediaType)"/> with <see cref="MediaType.Screen"/>597 /// </summary>598 /// <returns>Task which resolves to a <see cref="byte"/>[] containing the PDF data.</returns>599 /// <remarks>600 /// Generating a pdf is currently only supported in Chrome headless601 /// </remarks>602 public Task<byte[]> PdfDataAsync() => PdfDataAsync(new PdfOptions());603 /// <summary>604 /// Generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaAsync(MediaType)"/> with <see cref="MediaType.Screen"/>605 /// </summary>606 /// <param name="options">pdf options</param>607 /// <returns>Task which resolves to a <see cref="byte"/>[] containing the PDF data.</returns>608 /// <remarks>609 /// Generating a pdf is currently only supported in Chrome headless610 /// </remarks>611 public Task<byte[]> PdfDataAsync(PdfOptions options) => PdfInternalAsync(null, options);612 internal async Task<byte[]> PdfInternalAsync(string file, PdfOptions options)613 {614 var paperWidth = PaperFormat.Letter.Width;615 var paperHeight = PaperFormat.Letter.Height;616 if (options.Format != null)617 {618 paperWidth = options.Format.Width;619 paperHeight = options.Format.Height;620 }621 else622 {623 if (options.Width != null)624 {625 paperWidth = ConvertPrintParameterToInches(options.Width);626 }627 if (options.Height != null)628 {629 paperHeight = ConvertPrintParameterToInches(options.Height);630 }631 }632 var marginTop = ConvertPrintParameterToInches(options.MarginOptions.Top);633 var marginLeft = ConvertPrintParameterToInches(options.MarginOptions.Left);634 var marginBottom = ConvertPrintParameterToInches(options.MarginOptions.Bottom);635 var marginRight = ConvertPrintParameterToInches(options.MarginOptions.Right);636 var result = await Client.SendAsync<PagePrintToPDFResponse>("Page.printToPDF", new PagePrintToPDFRequest637 {638 TransferMode = "ReturnAsStream",639 Landscape = options.Landscape,640 DisplayHeaderFooter = options.DisplayHeaderFooter,641 HeaderTemplate = options.HeaderTemplate,642 FooterTemplate = options.FooterTemplate,643 PrintBackground = options.PrintBackground,644 Scale = options.Scale,645 PaperWidth = paperWidth,646 PaperHeight = paperHeight,647 MarginTop = marginTop,648 MarginBottom = marginBottom,649 MarginLeft = marginLeft,650 MarginRight = marginRight,651 PageRanges = options.PageRanges,652 PreferCSSPageSize = options.PreferCSSPageSize653 }).ConfigureAwait(false);654 return await ProtocolStreamReader.ReadProtocolStreamByteAsync(Client, result.Stream, file).ConfigureAwait(false);655 }656 /// <summary>657 /// Enables/Disables Javascript on the page658 /// </summary>659 /// <returns>Task.</returns>660 /// <param name="enabled">Whether or not to enable JavaScript on the page.</param>661 public Task SetJavaScriptEnabledAsync(bool enabled)662 {663 if (enabled == JavascriptEnabled)664 {665 return Task.CompletedTask;666 }667 JavascriptEnabled = enabled;668 return Client.SendAsync("Emulation.setScriptExecutionDisabled", new EmulationSetScriptExecutionDisabledRequest669 {670 Value = !enabled671 });672 }673 /// <summary>674 /// Toggles bypassing page's Content-Security-Policy.675 /// </summary>676 /// <param name="enabled">sets bypassing of page's Content-Security-Policy.</param>677 /// <returns></returns>678 /// <remarks>679 /// CSP bypassing happens at the moment of CSP initialization rather then evaluation.680 /// Usually this means that <see cref="SetBypassCSPAsync(bool)"/> should be called before navigating to the domain.681 /// </remarks>682 public Task SetBypassCSPAsync(bool enabled) => Client.SendAsync("Page.setBypassCSP", new PageSetBypassCSPRequest683 {684 Enabled = enabled685 });686 /// <summary>687 /// Emulates a media such as screen or print.688 /// </summary>689 /// <returns>Task.</returns>690 /// <param name="media">Media to set.</param>691 [Obsolete("User EmulateMediaTypeAsync instead")]692 public Task EmulateMediaAsync(MediaType media) => EmulateMediaTypeAsync(media);693 /// <summary>694 /// Emulates a media such as screen or print.695 /// </summary>696 /// <param name="type">Media to set.</param>697 /// <example>698 /// <code>699 /// <![CDATA[700 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('screen').matches)");701 /// // â true702 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('print').matches)");703 /// // â true704 /// await page.EmulateMediaTypeAsync(MediaType.Print);705 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('screen').matches)");706 /// // â false707 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('print').matches)");708 /// // â true709 /// await page.EmulateMediaTypeAsync(MediaType.None);710 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('screen').matches)");711 /// // â true712 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('print').matches)");713 /// // â true714 /// ]]>715 /// </code>716 /// </example>717 /// <returns>Emulate media type task.</returns>718 public Task EmulateMediaTypeAsync(MediaType type)719 => Client.SendAsync("Emulation.setEmulatedMedia", new EmulationSetEmulatedMediaTypeRequest { Media = type });720 /// <summary>721 /// Given an array of media feature objects, emulates CSS media features on the page.722 /// </summary>723 /// <param name="features">Features to apply</param>724 /// <example>725 /// <code>726 /// <![CDATA[727 /// await page.EmulateMediaFeaturesAsync(new MediaFeature[]{ new MediaFeature { MediaFeature = MediaFeature.PrefersColorScheme, Value = "dark" }});728 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: dark)').matches)");729 /// // â true730 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: light)').matches)");731 /// // â false732 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");733 /// // â false734 /// await page.EmulateMediaFeaturesAsync(new MediaFeature[]{ new MediaFeature { MediaFeature = MediaFeature.PrefersReducedMotion, Value = "reduce" }});735 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-reduced-motion: reduce)').matches)");736 /// // â true737 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");738 /// // â false739 /// await page.EmulateMediaFeaturesAsync(new MediaFeature[]740 /// { 741 /// new MediaFeature { MediaFeature = MediaFeature.PrefersColorScheme, Value = "dark" },742 /// new MediaFeature { MediaFeature = MediaFeature.PrefersReducedMotion, Value = "reduce" },743 /// });744 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: dark)').matches)");745 /// // â true746 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: light)').matches)");747 /// // â false748 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");749 /// // â false750 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-reduced-motion: reduce)').matches)");751 /// // â true752 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");753 /// // â false754 /// ]]>755 /// </code>756 /// </example>757 /// <returns>Emulate features task</returns>758 public Task EmulateMediaFeaturesAsync(IEnumerable<MediaFeatureValue> features)759 => Client.SendAsync("Emulation.setEmulatedMedia", new EmulationSetEmulatedMediaFeatureRequest { Features = features });760 /// <summary>761 /// Sets the viewport.762 /// In the case of multiple pages in a single browser, each page can have its own viewport size.763 /// <see cref="SetViewportAsync(ViewPortOptions)"/> will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport before navigating to the page.764 /// </summary>765 /// <example>766 ///<![CDATA[...
PuppeteerBrowserBuilder.cs
Source:PuppeteerBrowserBuilder.cs
...379 var elementToclick = await page.WaitForXPathAsync(xPath);380 if (elementToclick != null) 381 {382 await elementToclick.ClickAsync();383 return await page.EvaluateFunctionAsync<string>("() => navigator.clipboard.readText()");384 }385 _logger.Debug("GetVideoAdsOnUrl: elementToclick is null");386 return null;387 }388 /// <summary>389 /// Returns IpDetails by the specified url390 /// </summary>391 /// <param name="ipFetcherUrl">The ip details provider url.</param>392 /// <returns>The instance of <see cref="IpDetails"></see></returns>393 async Task<IpDetails> IPuppeteerBrowser.GetIpDetails(string ipFetcherUrl)394 {395 IpDetails ipDetails = await GetIpDetailsInternal(ipFetcherUrl);396 return ipDetails ?? new IpDetails397 {398 City = "N/A",399 ContinentName = "N/A",400 CountryCode = "N/A",401 CountryName = "N/A",402 IpAddress = "127.0.0.1",403 State = "N/A",404 ContinentCode = "N/A"405 };406 }407 /// <summary>408 /// Returns IpDetails by the specified url and, in case of error, returns the default country code and country name409 /// </summary>410 /// <param name="ipFetcherUrl">The ip details provider url.</param>411 /// <param name="defaultCountryCode">The country code tu return default details.</param>412 /// <returns>The instance of <see cref="IpDetails"></see></returns>413 async Task<IpDetails> IPuppeteerBrowser.GetIpDetails(string ipFetcherUrl, string defaultCountryCode)414 {415 IpDetails ipDetails = await GetIpDetailsInternal(ipFetcherUrl);416 return ipDetails ?? new IpDetails417 {418 City = "N/A",419 ContinentName = "N/A",420 CountryCode = defaultCountryCode,421 CountryName = References.Countries[defaultCountryCode],422 IpAddress = "127.0.0.1",423 State = "N/A",424 ContinentCode = "N/A"425 };426 }427 async Task<string> IPuppeteerBrowser.GetPageContent(string stringUrl, params WaitUntilNavigation[] waitUntilNavigations)428 {429 return await GetPageContentInternalAsync(stringUrl, waitUntilNavigations);430 }431 private async Task SetPageOptions(Page page)432 {433 var viewPortOptions = new ViewPortOptions434 { Width = _browserConfig.WindowWidth, Height = _browserConfig.WindowHeight };435 await page.SetViewportAsync(viewPortOptions);436 if (!string.IsNullOrWhiteSpace(_puppeteerContext.ProxyUserName))437 {438 await page.AuthenticateAsync(new Credentials439 {440 Username = _puppeteerContext.ProxyUserName,441 Password = _puppeteerContext.ProxyPwd442 });443 }444 }445 async Task<Page> IPuppeteerBrowser.GetPage(string url, TimeSpan? timeoutPageLoad, params WaitUntilNavigation[] waitUntilNavigations)446 {447 var page = await GoToPageAsync(url, timeoutPageLoad, waitUntilNavigations);448 if (_overridePermissions?.Any() ?? false)449 {450 await page.BrowserContext.OverridePermissionsAsync(page.Url,451 new []452 {453 OverridePermission.ClipboardWrite, OverridePermission.ClipboardRead,454 OverridePermission.AccessibilityEvents, OverridePermission.BackgroundSync,455 OverridePermission.Geolocation, OverridePermission.Microphone, OverridePermission.Notifications,456 OverridePermission.PaymentHandler/*, OverridePermission.Push*/457 });458 }459 return page;460 }461 async Task<string> IPuppeteerBrowser.GetScrolledPage(string url, int maxScroll, params WaitUntilNavigation[] waitUntilNavigations)462 {463 var pageResult = string.Empty;464 try465 {466 using (var page = await GoToPageAsync(url, null, waitUntilNavigations))467 {468 await ScrollPageSync(page, TimeSpan.FromMilliseconds(100));469 pageResult = await page.GetContentAsync();470 }471 }472 catch (Exception ex)473 {474 _logger.Error(ex);475 }476 return pageResult;477 }478 async Task IPuppeteerBrowser.ScrollPageSync(Page page, int maxScroll = 40000, int step = 200)479 {480 await ScrollPageSync(page, TimeSpan.FromMilliseconds(100), maxScroll, step);481 }482 /// <summary>483 /// Return state of page permission. Exmp: permissionName=clipboard-read484 /// </summary>485 /// <returns></returns>486 async Task<string> IPuppeteerBrowser.GetPagePermission(Page page, string permissionName)487 {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)...
TargetTests.cs
Source:TargetTests.cs
...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()123 {124 await Page.GoToAsync(TestConstants.EmptyPage);125 await Page.EvaluateFunctionAsync(@"() =>126 {127 new SharedWorker('data:text/javascript,console.log(""hi"")');128 }");129 var target = await Context.WaitForTargetAsync(t => t.Type == TargetType.SharedWorker);130 var worker = await target.WorkerAsync();131 Assert.Equal("[object SharedWorkerGlobalScope]", await worker.EvaluateFunctionAsync("() => self.toString()"));132 }133 [PuppeteerTest("target.spec.ts", "Target", "should report when a target url changes")]134 [SkipBrowserFact(skipFirefox: true)]135 public async Task ShouldReportWhenATargetUrlChanges()136 {137 await Page.GoToAsync(TestConstants.EmptyPage);138 var changedTargetTaskCompletion = new TaskCompletionSource<Target>();139 void ChangedTargetEventHandler(object sender, TargetChangedArgs e)140 {141 changedTargetTaskCompletion.SetResult(e.Target);142 Context.TargetChanged -= ChangedTargetEventHandler;143 }144 Context.TargetChanged += ChangedTargetEventHandler;145 await Page.GoToAsync(TestConstants.CrossProcessUrl + "/");...
NavigateCollect.cs
Source:NavigateCollect.cs
...134 {135 var elcurrentpagelink = await this.Page.XPathAsync("//*[@id='TableTabContent']/div[3]/div[2]/a[@class='activePage']");136 if (elcurrentpagelink.Length > 0)137 {138 var href = await this.Page.EvaluateFunctionAsync<string>("el => el.href ", elcurrentpagelink.First());139 var start = href.IndexOf("(") + 1;140 var end = href.IndexOf(",");141 var currpage = href.Substring(start, end - start);142 return int.Parse(currpage);143 }144 return -1;145 }146 private async Task<int> GetTotalPages()147 {148 var ellastpagelink = await this.Page.QuerySelectorAsync("a[title='Last page']");149 if (ellastpagelink != null)150 {151 var href = await this.Page.EvaluateFunctionAsync<string>("el => el.href ", ellastpagelink);152 var start = href.IndexOf("(") + 1;153 var end = href.IndexOf(",");154 var totalpages = href.Substring(start, end - start);155 var result = int.Parse(totalpages);156 return result;157 }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();...
Worker.cs
Source:Worker.cs
...86 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.87 /// <see cref="JSHandle"/> instances can be passed as arguments88 /// </remarks>89 /// <returns>Task which resolves to script return value</returns>90 public async Task<JToken> EvaluateFunctionAsync(string script, params object[] args)91 => await (await ExecutionContextTask.ConfigureAwait(false)).EvaluateFunctionAsync(script, args).ConfigureAwait(false);92 /// <summary>93 /// Executes a function in the context94 /// </summary>95 /// <typeparam name="T">The type to deserialize the result to</typeparam>96 /// <param name="script">Script to be evaluated in browser context</param>97 /// <param name="args">Arguments to pass to script</param>98 /// <remarks>99 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.100 /// <see cref="JSHandle"/> instances can be passed as arguments101 /// </remarks>102 /// <returns>Task which resolves to script return value</returns>103 public async Task<T> EvaluateFunctionAsync<T>(string script, params object[] args)104 => await (await ExecutionContextTask.ConfigureAwait(false)).EvaluateFunctionAsync<T>(script, args).ConfigureAwait(false);105 /// <summary>106 /// Executes a script in browser context107 /// </summary>108 /// <param name="script">Script to be evaluated in browser context</param>109 /// <remarks>110 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.111 /// </remarks>112 /// <returns>Task which resolves to script return value</returns>113 /// <seealso cref="ExecutionContext.EvaluateExpressionHandleAsync(string)"/>114 public async Task<JSHandle> EvaluateExpressionHandleAsync(string script)115 => await (await ExecutionContextTask.ConfigureAwait(false)).EvaluateExpressionHandleAsync(script).ConfigureAwait(false);116 internal Task<ExecutionContext> ExecutionContextTask => _executionContextCallback.Task;117 internal async void OnMessageReceived(object sender, MessageEventArgs e)118 {...
PageWorkerTests.cs
Source:PageWorkerTests.cs
...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
...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}...
ResponseFromServiceWorkerTests.cs
Source:ResponseFromServiceWorkerTests.cs
...24 var responses = new Dictionary<string, Response>();25 Page.Response += (sender, e) => responses[e.Response.Url.Split('/').Last()] = e.Response;26 await Page.GoToAsync(TestConstants.ServerUrl + "/serviceworkers/fetch/sw.html",27 waitUntil: new[] { WaitUntilNavigation.Networkidle2 });28 await Page.EvaluateFunctionAsync("async () => await window.activationPromise");29 await Page.ReloadAsync();3031 Assert.Equal(2, responses.Count);32 Assert.Equal(HttpStatusCode.OK, responses["sw.html"].Status);33 Assert.True(responses["sw.html"].FromServiceWorker);34 Assert.Equal(HttpStatusCode.OK, responses["style.css"].Status);35 Assert.True(responses["style.css"].FromServiceWorker);36 }37 }38}
EvaluateFunctionAsync
Using AI Code Generation
1using System.Threading.Tasks;2using PuppeteerSharp;3{4 {5 static void Main(string[] args)6 {7 MainAsync().Wait();8 }9 static async Task MainAsync()10 {11 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });12 var page = await browser.NewPageAsync();13 var worker = await page.EvaluateHandleAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], {type: 'application/javascript'})))");14 await page.EvaluateExpressionAsync("() => new Promise(f => requestAnimationFrame(() => requestAnimationFrame(f)))");15 var result = await worker.EvaluateFunctionAsync<string>("() => 1 + 2");16 System.Console.WriteLine(result);17 await browser.CloseAsync();18 }19 }20}
EvaluateFunctionAsync
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 {13 Args = new string[] { "--disable-web-security" }14 };15 using (var browser = await Puppeteer.LaunchAsync(options))16 {17 var page = await browser.NewPageAsync();18 var worker = await page.WaitForFunctionAsync("!!window.Worker");19 var result = await worker.EvaluateFunctionAsync("() => 1 + 1");20 Console.WriteLine(result);21 }22 }23 }24}25PuppeteerSharp.Worker.EvaluateFunctionAsync Method (String, Object[])26PuppeteerSharp.Worker.EvaluateFunctionAsync Method (String, Object)27PuppeteerSharp.Worker.EvaluateFunctionAsync Method (String)28PuppeteerSharp.Worker.EvaluateFunctionAsync Method (String, Object, Object)29PuppeteerSharp.Worker.EvaluateFunctionAsync Method (String, Object, Object, Object)30PuppeteerSharp.Worker.EvaluateFunctionAsync Method (String, Object, Object, Object, Object)31PuppeteerSharp.Worker.EvaluateFunctionAsync Method (String, Object, Object, Object, Object, Object)32PuppeteerSharp.Worker.EvaluateFunctionAsync Method (String, Object, Object, Object, Object, Object, Object)33PuppeteerSharp.Worker.EvaluateFunctionAsync Method (String, Object, Object, Object, Object, Object, Object, Object)34PuppeteerSharp.Worker.EvaluateFunctionAsync Method (String, Object, Object, Object, Object, Object, Object, Object, Object)35PuppeteerSharp.Worker.EvaluateFunctionAsync Method (String, Object, Object, Object, Object, Object, Object, Object, Object, Object)36PuppeteerSharp.Worker.EvaluateFunctionAsync Method (String, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object)37PuppeteerSharp.Worker.EvaluateFunctionAsync Method (String, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object
EvaluateFunctionAsync
Using AI Code Generation
1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3 Args = new string[] { "--no-sandbox" }4});5var page = await browser.NewPageAsync();6await page.SetContentAsync(@"7 var worker = new Worker('worker.js');8 worker.onmessage = function (e) {9 document.body.innerHTML = e.data;10 };11");12await page.AddScriptTagAsync(new AddTagOptions13{14});15await page.EvaluateFunctionAsync(@"16 async function () {17 var worker = new Worker('worker.js');18 worker.onmessage = function (e) {19 document.body.innerHTML = e.data;20 };21 }22");23await page.EvaluateFunctionAsync(@"24 async function () {25 var worker = new Worker('worker.js');26 worker.onmessage = function (e) {27 document.body.innerHTML = e.data;28 };29 }30");31await page.EvaluateFunctionAsync(@"32 async function () {33 var worker = new Worker('worker.js');34 worker.onmessage = function (e) {35 document.body.innerHTML = e.data;36 };37 }38");39await page.EvaluateFunctionAsync(@"40 async function () {41 var worker = new Worker('worker.js');42 worker.onmessage = function (e) {43 document.body.innerHTML = e.data;44 };45 }46");47var worker = await page.WorkerAsync();48await worker.EvaluateFunctionAsync("function () { postMessage('Hello from worker'); }");49await page.WaitForFunctionAsync("document.body.textContent.includes('Hello from worker')");50await browser.CloseAsync();51postMessage('Hello from worker');52var browser = await Puppeteer.LaunchAsync(new LaunchOptions53{54 Args = new string[] { "--no-sandbox" }55});56var page = await browser.NewPageAsync();57await page.SetContentAsync(@"58 var worker = new Worker('worker
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!!