Best Puppeteer-sharp code snippet using PuppeteerSharp.PuppeteerHandleExtensions.EvaluateFunctionAsync
Page.cs
Source:Page.cs  
...441        /// <seealso cref="Frame.QuerySelectorAllAsync(string)"/>442        public Task<ElementHandle[]> QuerySelectorAllAsync(string selector)443            => MainFrame.QuerySelectorAllAsync(selector);444        /// <summary>445        /// A utility function to be used with <see cref="PuppeteerHandleExtensions.EvaluateFunctionAsync{T}(Task{JSHandle}, string, object[])"/>446        /// </summary>447        /// <param name="selector">A selector to query page for</param>448        /// <returns>Task which resolves to a <see cref="JSHandle"/> of <c>document.querySelectorAll</c> result</returns>449        public Task<JSHandle> QuerySelectorAllHandleAsync(string selector)450            => EvaluateFunctionHandleAsync("selector => Array.from(document.querySelectorAll(selector))", selector);451        /// <summary>452        /// Evaluates the XPath expression453        /// </summary>454        /// <param name="expression">Expression to evaluate <see href="https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate"/></param>455        /// <returns>Task which resolves to an array of <see cref="ElementHandle"/></returns>456        /// <remarks>457        /// Shortcut for <c>page.MainFrame.XPathAsync(expression)</c>458        /// </remarks>459        /// <seealso cref="Frame.XPathAsync(string)"/>460        public Task<ElementHandle[]> XPathAsync(string expression) => MainFrame.XPathAsync(expression);461        /// <summary>462        /// Executes a script in browser context463        /// </summary>464        /// <param name="script">Script to be evaluated in browser context</param>465        /// <remarks>466        /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.467        /// </remarks>468        /// <returns>Task which resolves to script return value</returns>469        public async Task<JSHandle> EvaluateExpressionHandleAsync(string script)470        {471            var context = await MainFrame.GetExecutionContextAsync().ConfigureAwait(false);472            return await context.EvaluateExpressionHandleAsync(script).ConfigureAwait(false);473        }474        /// <summary>475        /// Executes a script in browser context476        /// </summary>477        /// <param name="pageFunction">Script to be evaluated in browser context</param>478        /// <param name="args">Function arguments</param>479        /// <remarks>480        /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.481        /// <see cref="JSHandle"/> instances can be passed as arguments482        /// </remarks>483        /// <returns>Task which resolves to script return value</returns>484        public async Task<JSHandle> EvaluateFunctionHandleAsync(string pageFunction, params object[] args)485        {486            var context = await MainFrame.GetExecutionContextAsync().ConfigureAwait(false);487            return await context.EvaluateFunctionHandleAsync(pageFunction, args).ConfigureAwait(false);488        }489        /// <summary>490        /// Adds a function which would be invoked in one of the following scenarios:491        /// - whenever the page is navigated492        /// - whenever the child frame is attached or navigated. In this case, the function is invoked in the context of the newly attached frame493        /// </summary>494        /// <param name="pageFunction">Function to be evaluated in browser context</param>495        /// <param name="args">Arguments to pass to <c>pageFunction</c></param>496        /// <remarks>497        /// The function is invoked after the document was created but before any of its scripts were run. This is useful to amend JavaScript environment, e.g. to seed <c>Math.random</c>.498        /// </remarks>499        /// <example>500        /// An example of overriding the navigator.languages property before the page loads:501        /// <code>502        /// await page.EvaluateOnNewDocumentAsync("() => window.__example = true");503        /// </code>504        /// </example>505        /// <returns>Task</returns>506        [Obsolete("User EvaluateFunctionOnNewDocumentAsync instead")]507        public Task EvaluateOnNewDocumentAsync(string pageFunction, params object[] args)508            => EvaluateFunctionOnNewDocumentAsync(pageFunction, args);509        /// <summary>510        /// Adds a function which would be invoked in one of the following scenarios:511        /// - whenever the page is navigated512        /// - whenever the child frame is attached or navigated. In this case, the function is invoked in the context of the newly attached frame513        /// </summary>514        /// <param name="pageFunction">Function to be evaluated in browser context</param>515        /// <param name="args">Arguments to pass to <c>pageFunction</c></param>516        /// <remarks>517        /// The function is invoked after the document was created but before any of its scripts were run. This is useful to amend JavaScript environment, e.g. to seed <c>Math.random</c>.518        /// </remarks>519        /// <example>520        /// An example of overriding the navigator.languages property before the page loads:521        /// <code>522        /// await page.EvaluateFunctionOnNewDocumentAsync("() => window.__example = true");523        /// </code>524        /// </example>525        /// <returns>Task</returns>526        public Task EvaluateFunctionOnNewDocumentAsync(string pageFunction, params object[] args)527        {528            var source = EvaluationString(pageFunction, args);529            return Client.SendAsync("Page.addScriptToEvaluateOnNewDocument", new PageAddScriptToEvaluateOnNewDocumentRequest530            {531                Source = source532            });533        }534        /// <summary>535        /// Adds a function which would be invoked in one of the following scenarios:536        /// - whenever the page is navigated537        /// - whenever the child frame is attached or navigated. In this case, the function is invoked in the context of the newly attached frame538        /// </summary>539        /// <param name="expression">Javascript expression to be evaluated in browser context</param>540        /// <remarks>541        /// The function is invoked after the document was created but before any of its scripts were run. This is useful to amend JavaScript environment, e.g. to seed <c>Math.random</c>.542        /// </remarks>543        /// <example>544        /// An example of overriding the navigator.languages property before the page loads:545        /// <code>546        /// await page.EvaluateExpressionOnNewDocumentAsync("window.__example = true;");547        /// </code>548        /// </example>549        /// <returns>Task</returns>550        public Task EvaluateExpressionOnNewDocumentAsync(string expression)551            => Client.SendAsync("Page.addScriptToEvaluateOnNewDocument", new PageAddScriptToEvaluateOnNewDocumentRequest552            {553                Source = expression554            });555        /// <summary>556        /// The method iterates JavaScript heap and finds all the objects with the given prototype.557        /// Shortcut for <c>page.MainFrame.GetExecutionContextAsync().QueryObjectsAsync(prototypeHandle)</c>.558        /// </summary>559        /// <returns>A task which resolves to a handle to an array of objects with this prototype.</returns>560        /// <param name="prototypeHandle">A handle to the object prototype.</param>561        public async Task<JSHandle> QueryObjectsAsync(JSHandle prototypeHandle)562        {563            var context = await MainFrame.GetExecutionContextAsync().ConfigureAwait(false);564            return await context.QueryObjectsAsync(prototypeHandle).ConfigureAwait(false);565        }566        /// <summary>567        /// Activating request interception enables <see cref="PuppeteerSharp.Request.AbortAsync(RequestAbortErrorCode)">request.AbortAsync</see>,568        /// <see cref="PuppeteerSharp.Request.ContinueAsync(Payload)">request.ContinueAsync</see> and <see cref="PuppeteerSharp.Request.RespondAsync(ResponseData)">request.RespondAsync</see> methods.569        /// </summary>570        /// <returns>The request interception task.</returns>571        /// <param name="value">Whether to enable request interception..</param>572        public Task SetRequestInterceptionAsync(bool value)573            => FrameManager.NetworkManager.SetRequestInterceptionAsync(value);574        /// <summary>575        /// Set offline mode for the page.576        /// </summary>577        /// <returns>Result task</returns>578        /// <param name="value">When <c>true</c> enables offline mode for the page.</param>579        public Task SetOfflineModeAsync(bool value) => FrameManager.NetworkManager.SetOfflineModeAsync(value);580        /// <summary>581        /// Emulates network conditions582        /// </summary>583        /// <param name="networkConditions">Passing <c>null</c> disables network condition emulation.</param>584        /// <returns>Result task</returns>585        /// <remarks>586        /// **NOTE** This does not affect WebSockets and WebRTC PeerConnections (see https://crbug.com/563644)587        /// </remarks>588        public Task EmulateNetworkConditionsAsync(NetworkConditions networkConditions) => FrameManager.NetworkManager.EmulateNetworkConditionsAsync(networkConditions);589        /// <summary>590        /// Returns the page's cookies591        /// </summary>592        /// <param name="urls">Url's to return cookies for</param>593        /// <returns>Array of cookies</returns>594        /// <remarks>595        /// If no URLs are specified, this method returns cookies for the current page URL.596        /// If URLs are specified, only cookies for those URLs are returned.597        /// </remarks>598        public async Task<CookieParam[]> GetCookiesAsync(params string[] urls)599            => (await Client.SendAsync<NetworkGetCookiesResponse>("Network.getCookies", new NetworkGetCookiesRequest600            {601                Urls = urls.Length > 0 ? urls : new string[] { Url }602            }).ConfigureAwait(false)).Cookies;603        /// <summary>604        /// Clears all of the current cookies and then sets the cookies for the page605        /// </summary>606        /// <param name="cookies">Cookies to set</param>607        /// <returns>Task</returns>608        public async Task SetCookieAsync(params CookieParam[] cookies)609        {610            foreach (var cookie in cookies)611            {612                if (string.IsNullOrEmpty(cookie.Url) && Url.StartsWith("http", StringComparison.Ordinal))613                {614                    cookie.Url = Url;615                }616                if (cookie.Url == "about:blank")617                {618                    throw new PuppeteerException($"Blank page can not have cookie \"{cookie.Name}\"");619                }620            }621            await DeleteCookieAsync(cookies).ConfigureAwait(false);622            if (cookies.Length > 0)623            {624                await Client.SendAsync("Network.setCookies", new NetworkSetCookiesRequest625                {626                    Cookies = cookies627                }).ConfigureAwait(false);628            }629        }630        /// <summary>631        /// Deletes cookies from the page632        /// </summary>633        /// <param name="cookies">Cookies to delete</param>634        /// <returns>Task</returns>635        public async Task DeleteCookieAsync(params CookieParam[] cookies)636        {637            var pageURL = Url;638            foreach (var cookie in cookies)639            {640                if (string.IsNullOrEmpty(cookie.Url) && pageURL.StartsWith("http", StringComparison.Ordinal))641                {642                    cookie.Url = pageURL;643                }644                await Client.SendAsync("Network.deleteCookies", cookie).ConfigureAwait(false);645            }646        }647        /// <summary>648        /// Adds a <c><![CDATA[<script>]]></c> tag into the page with the desired url or content649        /// </summary>650        /// <param name="options">add script tag options</param>651        /// <remarks>652        /// Shortcut for <c>page.MainFrame.AddScriptTagAsync(options)</c>653        /// </remarks>654        /// <returns>Task which resolves to the added tag when the script's onload fires or when the script content was injected into frame</returns>655        /// <seealso cref="Frame.AddScriptTagAsync(AddTagOptions)"/>656        public Task<ElementHandle> AddScriptTagAsync(AddTagOptions options) => MainFrame.AddScriptTagAsync(options);657        /// <summary>658        /// Adds a <c><![CDATA[<script>]]></c> tag into the page with the desired url or content659        /// </summary>660        /// <param name="url">script url</param>661        /// <remarks>662        /// Shortcut for <c>page.MainFrame.AddScriptTagAsync(new AddTagOptions { Url = url })</c>663        /// </remarks>664        /// <returns>Task which resolves to the added tag when the script's onload fires or when the script content was injected into frame</returns>665        public Task<ElementHandle> AddScriptTagAsync(string url) => AddScriptTagAsync(new AddTagOptions { Url = url });666        /// <summary>667        /// 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 content668        /// </summary>669        /// <param name="options">add style tag options</param>670        /// <remarks>671        /// Shortcut for <c>page.MainFrame.AddStyleTagAsync(options)</c>672        /// </remarks>673        /// <returns>Task which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame</returns>674        /// <seealso cref="Frame.AddStyleTag(AddTagOptions)"/>675        public Task<ElementHandle> AddStyleTagAsync(AddTagOptions options) => MainFrame.AddStyleTagAsync(options);676        /// <summary>677        /// 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 content678        /// </summary>679        /// <param name="url">stylesheel url</param>680        /// <remarks>681        /// Shortcut for <c>page.MainFrame.AddStyleTagAsync(new AddTagOptions { Url = url })</c>682        /// </remarks>683        /// <returns>Task which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame</returns>684        public Task<ElementHandle> AddStyleTagAsync(string url) => AddStyleTagAsync(new AddTagOptions { Url = url });685        /// <summary>686        /// Adds a function called <c>name</c> on the page's <c>window</c> object.687        /// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves when <paramref name="puppeteerFunction"/> completes.688        /// </summary>689        /// <param name="name">Name of the function on the window object</param>690        /// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>691        /// <remarks>692        /// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.693        /// Functions installed via <see cref="ExposeFunctionAsync(string, Action)"/> survive navigations694        /// </remarks>695        /// <returns>Task</returns>696        public Task ExposeFunctionAsync(string name, Action puppeteerFunction)697            => ExposeFunctionAsync(name, (Delegate)puppeteerFunction);698        /// <summary>699        /// Adds a function called <c>name</c> on the page's <c>window</c> object.700        /// 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"/>.701        /// </summary>702        /// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>703        /// <param name="name">Name of the function on the window object</param>704        /// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>705        /// <remarks>706        /// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.707        /// Functions installed via <see cref="ExposeFunctionAsync{TResult}(string, Func{TResult})"/> survive navigations708        /// </remarks>709        /// <returns>Task</returns>710        public Task ExposeFunctionAsync<TResult>(string name, Func<TResult> puppeteerFunction)711            => ExposeFunctionAsync(name, (Delegate)puppeteerFunction);712        /// <summary>713        /// Adds a function called <c>name</c> on the page's <c>window</c> object.714        /// 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"/>.715        /// </summary>716        /// <typeparam name="T">The parameter of <paramref name="puppeteerFunction"/></typeparam>717        /// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>718        /// <param name="name">Name of the function on the window object</param>719        /// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>720        /// <remarks>721        /// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.722        /// Functions installed via <see cref="ExposeFunctionAsync{T, TResult}(string, Func{T, TResult})"/> survive navigations723        /// </remarks>724        /// <returns>Task</returns>725        public Task ExposeFunctionAsync<T, TResult>(string name, Func<T, TResult> puppeteerFunction)726            => ExposeFunctionAsync(name, (Delegate)puppeteerFunction);727        /// <summary>728        /// Adds a function called <c>name</c> on the page's <c>window</c> object.729        /// 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"/>.730        /// </summary>731        /// <typeparam name="T1">The first parameter of <paramref name="puppeteerFunction"/></typeparam>732        /// <typeparam name="T2">The second parameter of <paramref name="puppeteerFunction"/></typeparam>733        /// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>734        /// <param name="name">Name of the function on the window object</param>735        /// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>736        /// <remarks>737        /// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.738        /// Functions installed via <see cref="ExposeFunctionAsync{T1, T2, TResult}(string, Func{T1, T2, TResult})"/> survive navigations739        /// </remarks>740        /// <returns>Task</returns>741        public Task ExposeFunctionAsync<T1, T2, TResult>(string name, Func<T1, T2, TResult> puppeteerFunction)742            => ExposeFunctionAsync(name, (Delegate)puppeteerFunction);743        /// <summary>744        /// Adds a function called <c>name</c> on the page's <c>window</c> object.745        /// 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"/>.746        /// </summary>747        /// <typeparam name="T1">The first parameter of <paramref name="puppeteerFunction"/></typeparam>748        /// <typeparam name="T2">The second parameter of <paramref name="puppeteerFunction"/></typeparam>749        /// <typeparam name="T3">The third parameter of <paramref name="puppeteerFunction"/></typeparam>750        /// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>751        /// <param name="name">Name of the function on the window object</param>752        /// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>753        /// <remarks>754        /// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.755        /// Functions installed via <see cref="ExposeFunctionAsync{T1, T2, T3, TResult}(string, Func{T1, T2, T3, TResult})"/> survive navigations756        /// </remarks>757        /// <returns>Task</returns>758        public Task ExposeFunctionAsync<T1, T2, T3, TResult>(string name, Func<T1, T2, T3, TResult> puppeteerFunction)759            => ExposeFunctionAsync(name, (Delegate)puppeteerFunction);760        /// <summary>761        /// Adds a function called <c>name</c> on the page's <c>window</c> object.762        /// 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"/>.763        /// </summary>764        /// <typeparam name="T1">The first parameter of <paramref name="puppeteerFunction"/></typeparam>765        /// <typeparam name="T2">The second parameter of <paramref name="puppeteerFunction"/></typeparam>766        /// <typeparam name="T3">The third parameter of <paramref name="puppeteerFunction"/></typeparam>767        /// <typeparam name="T4">The fourth parameter of <paramref name="puppeteerFunction"/></typeparam>768        /// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>769        /// <param name="name">Name of the function on the window object</param>770        /// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>771        /// <remarks>772        /// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.773        /// Functions installed via <see cref="ExposeFunctionAsync{T1, T2, T3, T4, TResult}(string, Func{T1, T2, T3, T4, TResult})"/> survive navigations774        /// </remarks>775        /// <returns>Task</returns>776        public Task ExposeFunctionAsync<T1, T2, T3, T4, TResult>(string name, Func<T1, T2, T3, T4, TResult> puppeteerFunction)777            => ExposeFunctionAsync(name, (Delegate)puppeteerFunction);778        /// <summary>779        /// Gets the full HTML contents of the page, including the doctype.780        /// </summary>781        /// <returns>Task which resolves to the HTML content.</returns>782        /// <seealso cref="Frame.GetContentAsync"/>783        public Task<string> GetContentAsync() => FrameManager.MainFrame.GetContentAsync();784        /// <summary>785        /// Sets the HTML markup to the page786        /// </summary>787        /// <param name="html">HTML markup to assign to the page.</param>788        /// <param name="options">The navigations options</param>789        /// <returns>Task.</returns>790        /// <seealso cref="Frame.SetContentAsync(string, NavigationOptions)"/>791        public Task SetContentAsync(string html, NavigationOptions options = null) => FrameManager.MainFrame.SetContentAsync(html, options);792        /// <summary>793        /// Navigates to an url794        /// </summary>795        /// <remarks>796        /// <see cref="GoToAsync(string, int?, WaitUntilNavigation[])"/> will throw an error if:797        /// - there's an SSL error (e.g. in case of self-signed certificates).798        /// - target URL is invalid.799        /// - the `timeout` is exceeded during navigation.800        /// - the remote server does not respond or is unreachable.801        /// - the main resource failed to load.802        ///803        /// <see cref="GoToAsync(string, int?, WaitUntilNavigation[])"/> will not throw an error when any valid HTTP status code is returned by the remote server,804        /// including 404 "Not Found" and 500 "Internal Server Error".  The status code for such responses can be retrieved by calling <see cref="PuppeteerSharp.Response.Status"/>805        ///806        /// > **NOTE** <see cref="GoToAsync(string, int?, WaitUntilNavigation[])"/> either throws an error or returns a main resource response.807        /// The only exceptions are navigation to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.808        ///809        /// > **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>.810        ///811        /// Shortcut for <seealso cref="Frame.GoToAsync(string, int?, WaitUntilNavigation[])"/>812        /// </remarks>813        /// <param name="url">URL to navigate page to. The url should include scheme, e.g. https://.</param>814        /// <param name="options">Navigation parameters.</param>815        /// <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>816        /// <seealso cref="GoToAsync(string, int?, WaitUntilNavigation[])"/>817        public Task<Response> GoToAsync(string url, NavigationOptions options) => FrameManager.MainFrame.GoToAsync(url, options);818        /// <summary>819        /// Navigates to an url820        /// </summary>821        /// <param name="url">URL to navigate page to. The url should include scheme, e.g. https://.</param>822        /// <param name="timeout">Maximum navigation time in milliseconds, defaults to 30 seconds, pass <c>0</c> to disable timeout. </param>823        /// <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>824        /// <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>825        /// <seealso cref="GoToAsync(string, NavigationOptions)"/>826        public Task<Response> GoToAsync(string url, int? timeout = null, WaitUntilNavigation[] waitUntil = null)827            => GoToAsync(url, new NavigationOptions { Timeout = timeout, WaitUntil = waitUntil });828        /// <summary>829        /// Navigates to an url830        /// </summary>831        /// <param name="url">URL to navigate page to. The url should include scheme, e.g. https://.</param>832        /// <param name="waitUntil">When to consider navigation succeeded.</param>833        /// <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>834        /// <seealso cref="GoToAsync(string, NavigationOptions)"/>835        public Task<Response> GoToAsync(string url, WaitUntilNavigation waitUntil)836            => GoToAsync(url, new NavigationOptions { WaitUntil = new[] { waitUntil } });837        /// <summary>838        /// 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"/>839        /// </summary>840        /// <param name="file">The file path to save the PDF to. paths are resolved using <see cref="Path.GetFullPath(string)"/></param>841        /// <returns></returns>842        /// <remarks>843        /// Generating a pdf is currently only supported in Chrome headless844        /// </remarks>845        public Task PdfAsync(string file) => PdfAsync(file, new PdfOptions());846        /// <summary>847        ///  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"/>848        /// </summary>849        /// <param name="file">The file path to save the PDF to. paths are resolved using <see cref="Path.GetFullPath(string)"/></param>850        /// <param name="options">pdf options</param>851        /// <returns></returns>852        /// <remarks>853        /// Generating a pdf is currently only supported in Chrome headless854        /// </remarks>855        public async Task PdfAsync(string file, PdfOptions options)856        {857            if (options == null)858            {859                throw new ArgumentNullException(nameof(options));860            }861            await PdfInternalAsync(file, options).ConfigureAwait(false);862        }863        /// <summary>864        /// 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"/>865        /// </summary>866        /// <returns>Task which resolves to a <see cref="Stream"/> containing the PDF data.</returns>867        /// <remarks>868        /// Generating a pdf is currently only supported in Chrome headless869        /// </remarks>870        public Task<Stream> PdfStreamAsync() => PdfStreamAsync(new PdfOptions());871        /// <summary>872        /// 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"/>873        /// </summary>874        /// <param name="options">pdf options</param>875        /// <returns>Task which resolves to a <see cref="Stream"/> containing the PDF data.</returns>876        /// <remarks>877        /// Generating a pdf is currently only supported in Chrome headless878        /// </remarks>879        public async Task<Stream> PdfStreamAsync(PdfOptions options)880            => new MemoryStream(await PdfDataAsync(options).ConfigureAwait(false));881        /// <summary>882        /// 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"/>883        /// </summary>884        /// <returns>Task which resolves to a <see cref="byte"/>[] containing the PDF data.</returns>885        /// <remarks>886        /// Generating a pdf is currently only supported in Chrome headless887        /// </remarks>888        public Task<byte[]> PdfDataAsync() => PdfDataAsync(new PdfOptions());889        /// <summary>890        /// 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"/>891        /// </summary>892        /// <param name="options">pdf options</param>893        /// <returns>Task which resolves to a <see cref="byte"/>[] containing the PDF data.</returns>894        /// <remarks>895        /// Generating a pdf is currently only supported in Chrome headless896        /// </remarks>897        public Task<byte[]> PdfDataAsync(PdfOptions options)898        {899            if (options == null)900            {901                throw new ArgumentNullException(nameof(options));902            }903            return PdfInternalAsync(null, options);904        }905        internal async Task<byte[]> PdfInternalAsync(string file, PdfOptions options)906        {907            var paperWidth = PaperFormat.Letter.Width;908            var paperHeight = PaperFormat.Letter.Height;909            if (options.Format != null)910            {911                paperWidth = options.Format.Width;912                paperHeight = options.Format.Height;913            }914            else915            {916                if (options.Width != null)917                {918                    paperWidth = ConvertPrintParameterToInches(options.Width);919                }920                if (options.Height != null)921                {922                    paperHeight = ConvertPrintParameterToInches(options.Height);923                }924            }925            var marginTop = ConvertPrintParameterToInches(options.MarginOptions.Top);926            var marginLeft = ConvertPrintParameterToInches(options.MarginOptions.Left);927            var marginBottom = ConvertPrintParameterToInches(options.MarginOptions.Bottom);928            var marginRight = ConvertPrintParameterToInches(options.MarginOptions.Right);929            if (options.OmitBackground)930            {931                await SetTransparentBackgroundColorAsync().ConfigureAwait(false);932            }933            var result = await Client.SendAsync<PagePrintToPDFResponse>("Page.printToPDF", new PagePrintToPDFRequest934            {935                TransferMode = "ReturnAsStream",936                Landscape = options.Landscape,937                DisplayHeaderFooter = options.DisplayHeaderFooter,938                HeaderTemplate = options.HeaderTemplate,939                FooterTemplate = options.FooterTemplate,940                PrintBackground = options.PrintBackground,941                Scale = options.Scale,942                PaperWidth = paperWidth,943                PaperHeight = paperHeight,944                MarginTop = marginTop,945                MarginBottom = marginBottom,946                MarginLeft = marginLeft,947                MarginRight = marginRight,948                PageRanges = options.PageRanges,949                PreferCSSPageSize = options.PreferCSSPageSize950            }).ConfigureAwait(false);951            if (options.OmitBackground)952            {953                await ResetDefaultBackgroundColorAsync().ConfigureAwait(false);954            }955            return await ProtocolStreamReader.ReadProtocolStreamByteAsync(Client, result.Stream, file).ConfigureAwait(false);956        }957        /// <summary>958        /// Enables/Disables Javascript on the page959        /// </summary>960        /// <returns>Task.</returns>961        /// <param name="enabled">Whether or not to enable JavaScript on the page.</param>962        public Task SetJavaScriptEnabledAsync(bool enabled)963        {964            if (enabled == JavascriptEnabled)965            {966                return Task.CompletedTask;967            }968            JavascriptEnabled = enabled;969            return Client.SendAsync("Emulation.setScriptExecutionDisabled", new EmulationSetScriptExecutionDisabledRequest970            {971                Value = !enabled972            });973        }974        /// <summary>975        /// Toggles bypassing page's Content-Security-Policy.976        /// </summary>977        /// <param name="enabled">sets bypassing of page's Content-Security-Policy.</param>978        /// <returns></returns>979        /// <remarks>980        /// CSP bypassing happens at the moment of CSP initialization rather then evaluation.981        /// Usually this means that <see cref="SetBypassCSPAsync(bool)"/> should be called before navigating to the domain.982        /// </remarks>983        public Task SetBypassCSPAsync(bool enabled) => Client.SendAsync("Page.setBypassCSP", new PageSetBypassCSPRequest984        {985            Enabled = enabled986        });987        /// <summary>988        /// Emulates a media such as screen or print.989        /// </summary>990        /// <returns>Task.</returns>991        /// <param name="media">Media to set.</param>992        [Obsolete("User EmulateMediaTypeAsync instead")]993        public Task EmulateMediaAsync(MediaType media) => EmulateMediaTypeAsync(media);994        /// <summary>995        /// Emulates a media such as screen or print.996        /// </summary>997        /// <param name="type">Media to set.</param>998        /// <example>999        /// <code>1000        /// <![CDATA[1001        /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('screen').matches)");1002        /// // â true1003        /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('print').matches)");1004        /// // â true1005        /// await page.EmulateMediaTypeAsync(MediaType.Print);1006        /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('screen').matches)");1007        /// // â false1008        /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('print').matches)");1009        /// // â true1010        /// await page.EmulateMediaTypeAsync(MediaType.None);1011        /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('screen').matches)");1012        /// // â true1013        /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('print').matches)");1014        /// // â true1015        /// ]]>1016        /// </code>1017        /// </example>1018        /// <returns>Emulate media type task.</returns>1019        public Task EmulateMediaTypeAsync(MediaType type)1020            => Client.SendAsync("Emulation.setEmulatedMedia", new EmulationSetEmulatedMediaTypeRequest { Media = type });1021        /// <summary>1022        /// Given an array of media feature objects, emulates CSS media features on the page.1023        /// </summary>1024        /// <param name="features">Features to apply</param>1025        /// <example>1026        /// <code>1027        /// <![CDATA[1028        /// await page.EmulateMediaFeaturesAsync(new MediaFeature[]{ new MediaFeature { MediaFeature =  MediaFeature.PrefersColorScheme, Value = "dark" }});1029        /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: dark)').matches)");1030        /// // â true1031        /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: light)').matches)");1032        /// // â false1033        /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");1034        /// // â false1035        /// await page.EmulateMediaFeaturesAsync(new MediaFeature[]{ new MediaFeature { MediaFeature = MediaFeature.PrefersReducedMotion, Value = "reduce" }});1036        /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-reduced-motion: reduce)').matches)");1037        /// // â true1038        /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");1039        /// // â false1040        /// await page.EmulateMediaFeaturesAsync(new MediaFeature[]1041        /// {1042        ///   new MediaFeature { MediaFeature = MediaFeature.PrefersColorScheme, Value = "dark" },1043        ///   new MediaFeature { MediaFeature = MediaFeature.PrefersReducedMotion, Value = "reduce" },1044        /// });1045        /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: dark)').matches)");1046        /// // â true1047        /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: light)').matches)");1048        /// // â false1049        /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");1050        /// // â false1051        /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-reduced-motion: reduce)').matches)");1052        /// // â true1053        /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");1054        /// // â false1055        /// ]]>1056        /// </code>1057        /// </example>1058        /// <returns>Emulate features task</returns>1059        public Task EmulateMediaFeaturesAsync(IEnumerable<MediaFeatureValue> features)1060            => Client.SendAsync("Emulation.setEmulatedMedia", new EmulationSetEmulatedMediaFeatureRequest { Features = features });1061        /// <summary>1062        /// Sets the viewport.1063        /// In the case of multiple pages in a single browser, each page can have its own viewport size.1064        /// <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.1065        /// </summary>1066        /// <example>1067        ///<![CDATA[1068        /// using(var page = await browser.NewPageAsync())1069        /// {1070        ///     await page.SetViewPortAsync(new ViewPortOptions1071        ///     {1072        ///         Width = 640,1073        ///         Height = 480,1074        ///         DeviceScaleFactor = 11075        ///     });1076        ///     await page.goto('https://www.example.com');1077        /// }1078        /// ]]>1079        /// </example>1080        /// <returns>The viewport task.</returns>1081        /// <param name="viewport">Viewport options.</param>1082        public async Task SetViewportAsync(ViewPortOptions viewport)1083        {1084            if (viewport == null)1085            {1086                throw new ArgumentNullException(nameof(viewport));1087            }1088            var needsReload = await _emulationManager.EmulateViewport(viewport).ConfigureAwait(false);1089            Viewport = viewport;1090            if (needsReload)1091            {1092                await ReloadAsync().ConfigureAwait(false);1093            }1094        }1095        /// <summary>1096        /// Emulates given device metrics and user agent.1097        /// </summary>1098        /// <remarks>1099        /// This method is a shortcut for calling two methods:1100        /// <see cref="SetViewportAsync(ViewPortOptions)"/>1101        /// <see cref="SetUserAgentAsync(string)"/>1102        /// To aid emulation, puppeteer provides a list of device descriptors which can be obtained via the <see cref="Puppeteer.Devices"/>.1103        /// <see cref="EmulateAsync(DeviceDescriptor)"/> will resize the page. A lot of websites don't expect phones to change size, so you should emulate before navigating to the page.1104        /// </remarks>1105        /// <example>1106        ///<![CDATA[1107        /// var iPhone = Puppeteer.Devices[DeviceDescriptorName.IPhone6];1108        /// using(var page = await browser.NewPageAsync())1109        /// {1110        ///     await page.EmulateAsync(iPhone);1111        ///     await page.goto('https://www.google.com');1112        /// }1113        /// ]]>1114        /// </example>1115        /// <returns>Task.</returns>1116        /// <param name="options">Emulation options.</param>1117        public Task EmulateAsync(DeviceDescriptor options)1118        {1119            if (options == null)1120            {1121                throw new ArgumentNullException(nameof(options));1122            }1123            return Task.WhenAll(1124                SetViewportAsync(options.ViewPort),1125                SetUserAgentAsync(options.UserAgent));1126        }1127        /// <summary>1128        /// Takes a screenshot of the page1129        /// </summary>1130        /// <returns>The screenshot task.</returns>1131        /// <param name="file">The file path to save the image to. The screenshot type will be inferred from file extension.1132        /// If path is a relative path, then it is resolved relative to current working directory. If no path is provided,1133        /// the image won't be saved to the disk.</param>1134        public Task ScreenshotAsync(string file) => ScreenshotAsync(file, new ScreenshotOptions());1135        /// <summary>1136        /// Takes a screenshot of the page1137        /// </summary>1138        /// <returns>The screenshot task.</returns>1139        /// <param name="file">The file path to save the image to. The screenshot type will be inferred from file extension.1140        /// If path is a relative path, then it is resolved relative to current working directory. If no path is provided,1141        /// the image won't be saved to the disk.</param>1142        /// <param name="options">Screenshot options.</param>1143        public async Task ScreenshotAsync(string file, ScreenshotOptions options)1144        {1145            if (options == null)1146            {1147                throw new ArgumentNullException(nameof(options));1148            }1149            if (!options.Type.HasValue)1150            {1151                options.Type = ScreenshotOptions.GetScreenshotTypeFromFile(file);1152                if (options.Type == ScreenshotType.Jpeg && !options.Quality.HasValue)1153                {1154                    options.Quality = 90;1155                }1156            }1157            var data = await ScreenshotDataAsync(options).ConfigureAwait(false);1158            using (var fs = AsyncFileHelper.CreateStream(file, FileMode.Create))1159            {1160                await fs.WriteAsync(data, 0, data.Length).ConfigureAwait(false);1161            }1162        }1163        /// <summary>1164        /// Takes a screenshot of the page1165        /// </summary>1166        /// <returns>Task which resolves to a <see cref="Stream"/> containing the image data.</returns>1167        public Task<Stream> ScreenshotStreamAsync() => ScreenshotStreamAsync(new ScreenshotOptions());1168        /// <summary>1169        /// Takes a screenshot of the page1170        /// </summary>1171        /// <returns>Task which resolves to a <see cref="Stream"/> containing the image data.</returns>1172        /// <param name="options">Screenshot options.</param>1173        public async Task<Stream> ScreenshotStreamAsync(ScreenshotOptions options)1174            => new MemoryStream(await ScreenshotDataAsync(options).ConfigureAwait(false));1175        /// <summary>1176        /// Takes a screenshot of the page1177        /// </summary>1178        /// <returns>Task which resolves to a <see cref="string"/> containing the image data as base64.</returns>1179        public Task<string> ScreenshotBase64Async() => ScreenshotBase64Async(new ScreenshotOptions());1180        /// <summary>1181        /// Takes a screenshot of the page1182        /// </summary>1183        /// <returns>Task which resolves to a <see cref="string"/> containing the image data as base64.</returns>1184        /// <param name="options">Screenshot options.</param>1185        public Task<string> ScreenshotBase64Async(ScreenshotOptions options)1186        {1187            if (options == null)1188            {1189                throw new ArgumentNullException(nameof(options));1190            }1191            var screenshotType = options.Type;1192            if (!screenshotType.HasValue)1193            {1194                screenshotType = ScreenshotType.Png;1195            }1196            if (options.Quality.HasValue)1197            {1198                if (screenshotType != ScreenshotType.Jpeg)1199                {1200                    throw new ArgumentException($"options.Quality is unsupported for the {screenshotType} screenshots");1201                }1202                if (options.Quality < 0 || options.Quality > 100)1203                {1204                    throw new ArgumentException($"Expected options.quality to be between 0 and 100 (inclusive), got {options.Quality}");1205                }1206            }1207            if (options?.Clip?.Width == 0)1208            {1209                throw new PuppeteerException("Expected options.Clip.Width not to be 0.");1210            }1211            if (options?.Clip?.Height == 0)1212            {1213                throw new PuppeteerException("Expected options.Clip.Height not to be 0.");1214            }1215            if (options.Clip != null && options.FullPage)1216            {1217                throw new ArgumentException("options.clip and options.fullPage are exclusive");1218            }1219            return _screenshotTaskQueue.Enqueue(() => PerformScreenshot(screenshotType.Value, options));1220        }1221        /// <summary>1222        /// Takes a screenshot of the page1223        /// </summary>1224        /// <returns>Task which resolves to a <see cref="byte"/>[] containing the image data.</returns>1225        public Task<byte[]> ScreenshotDataAsync() => ScreenshotDataAsync(new ScreenshotOptions());1226        /// <summary>1227        /// Takes a screenshot of the page1228        /// </summary>1229        /// <returns>Task which resolves to a <see cref="byte"/>[] containing the image data.</returns>1230        /// <param name="options">Screenshot options.</param>1231        public async Task<byte[]> ScreenshotDataAsync(ScreenshotOptions options)1232            => Convert.FromBase64String(await ScreenshotBase64Async(options).ConfigureAwait(false));1233        /// <summary>1234        /// Returns page's title1235        /// </summary>1236        /// <returns>page's title</returns>1237        /// <see cref="Frame.GetTitleAsync"/>1238        public Task<string> GetTitleAsync() => MainFrame.GetTitleAsync();1239        /// <summary>1240        /// Closes the page.1241        /// </summary>1242        /// <param name="options">Close options.</param>1243        /// <returns>Task.</returns>1244        public Task CloseAsync(PageCloseOptions options = null)1245        {1246            if (!(Client?.Connection?.IsClosed ?? true))1247            {1248                var runBeforeUnload = options?.RunBeforeUnload ?? false;1249                if (runBeforeUnload)1250                {1251                    return Client.SendAsync("Page.close");1252                }1253                return Client.Connection.SendAsync("Target.closeTarget", new TargetCloseTargetRequest1254                {1255                    TargetId = Target.TargetId1256                }).ContinueWith(task => Target.CloseTask, TaskScheduler.Default);1257            }1258            _logger.LogWarning("Protocol error: Connection closed. Most likely the page has been closed.");1259            return _closeCompletedTcs.Task;1260        }1261        /// <summary>1262        /// Toggles ignoring cache for each request based on the enabled state. By default, caching is enabled.1263        /// </summary>1264        /// <param name="enabled">sets the <c>enabled</c> state of the cache</param>1265        /// <returns>Task</returns>1266        public Task SetCacheEnabledAsync(bool enabled = true)1267            => FrameManager.NetworkManager.SetCacheEnabledAsync(enabled);1268        /// <summary>1269        /// Fetches an element with <paramref name="selector"/>, scrolls it into view if needed, and then uses <see cref="Mouse"/> to click in the center of the element.1270        /// </summary>1271        /// <param name="selector">A selector to search for element to click. If there are multiple elements satisfying the selector, the first will be clicked.</param>1272        /// <param name="options">click options</param>1273        /// <exception cref="SelectorException">If there's no element matching <paramref name="selector"/></exception>1274        /// <returns>Task which resolves when the element matching <paramref name="selector"/> is successfully clicked</returns>1275        public Task ClickAsync(string selector, ClickOptions options = null) => FrameManager.MainFrame.ClickAsync(selector, options);1276        /// <summary>1277        /// Fetches an element with <paramref name="selector"/>, scrolls it into view if needed, and then uses <see cref="Mouse"/> to hover over the center of the element.1278        /// </summary>1279        /// <param name="selector">A selector to search for element to hover. If there are multiple elements satisfying the selector, the first will be hovered.</param>1280        /// <exception cref="SelectorException">If there's no element matching <paramref name="selector"/></exception>1281        /// <returns>Task which resolves when the element matching <paramref name="selector"/> is successfully hovered</returns>1282        public Task HoverAsync(string selector) => FrameManager.MainFrame.HoverAsync(selector);1283        /// <summary>1284        /// Fetches an element with <paramref name="selector"/> and focuses it1285        /// </summary>1286        /// <param name="selector">A selector to search for element to focus. If there are multiple elements satisfying the selector, the first will be focused.</param>1287        /// <exception cref="SelectorException">If there's no element matching <paramref name="selector"/></exception>1288        /// <returns>Task which resolves when the element matching <paramref name="selector"/> is successfully focused</returns>1289        public Task FocusAsync(string selector) => FrameManager.MainFrame.FocusAsync(selector);1290        /// <summary>1291        /// Sends a <c>keydown</c>, <c>keypress</c>/<c>input</c>, and <c>keyup</c> event for each character in the text.1292        /// </summary>1293        /// <param name="selector">A selector of an element to type into. If there are multiple elements satisfying the selector, the first will be used.</param>1294        /// <param name="text">A text to type into a focused element</param>1295        /// <param name="options">The options to apply to the type operation.</param>1296        /// <exception cref="SelectorException">If there's no element matching <paramref name="selector"/></exception>1297        /// <remarks>1298        /// To press a special key, like <c>Control</c> or <c>ArrowDown</c> use <see cref="PuppeteerSharp.Input.Keyboard.PressAsync(string, PressOptions)"/>1299        /// </remarks>1300        /// <example>1301        /// <code>1302        /// await page.TypeAsync("#mytextarea", "Hello"); // Types instantly1303        /// await page.TypeAsync("#mytextarea", "World", new TypeOptions { Delay = 100 }); // Types slower, like a user1304        /// </code>1305        /// </example>1306        /// <returns>Task</returns>1307        public Task TypeAsync(string selector, string text, TypeOptions options = null)1308            => FrameManager.MainFrame.TypeAsync(selector, text, options);1309        /// <summary>1310        /// Executes a script in browser context1311        /// </summary>1312        /// <param name="script">Script to be evaluated in browser context</param>1313        /// <remarks>1314        /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.1315        /// </remarks>1316        /// <example>1317        /// An example of scraping information from all hyperlinks on the page.1318        /// <code>1319        /// var hyperlinkInfo = await page.EvaluateExpressionAsync(@"1320        ///     Array1321        ///        .from(document.querySelectorAll('a'))1322        ///        .map(n => ({1323        ///            text: n.innerText,1324        ///            href: n.getAttribute('href'),1325        ///            target: n.getAttribute('target')1326        ///         }))1327        /// ");1328        /// Console.WriteLine(hyperlinkInfo.ToString()); // Displays JSON array of hyperlinkInfo objects1329        /// </code>1330        /// </example>1331        /// <seealso href="https://www.newtonsoft.com/json/help/html/t_newtonsoft_json_linq_jtoken.htm"/>1332        /// <seealso cref="EvaluateFunctionAsync{T}(string, object[])"/>1333        /// <returns>Task which resolves to script return value</returns>1334        public Task<JToken> EvaluateExpressionAsync(string script)1335            => FrameManager.MainFrame.EvaluateExpressionAsync<JToken>(script);1336        /// <summary>1337        /// Executes a script in browser context1338        /// </summary>1339        /// <typeparam name="T">The type to deserialize the result to</typeparam>1340        /// <param name="script">Script to be evaluated in browser context</param>1341        /// <remarks>1342        /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.1343        /// </remarks>1344        /// <seealso cref="EvaluateFunctionAsync{T}(string, object[])"/>1345        /// <returns>Task which resolves to script return value</returns>1346        public Task<T> EvaluateExpressionAsync<T>(string script)1347            => FrameManager.MainFrame.EvaluateExpressionAsync<T>(script);1348        /// <summary>1349        /// Executes a function in browser context1350        /// </summary>1351        /// <param name="script">Script to be evaluated in browser context</param>1352        /// <param name="args">Arguments to pass to script</param>1353        /// <remarks>1354        /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.1355        /// <see cref="JSHandle"/> instances can be passed as arguments1356        /// </remarks>1357        /// <seealso cref="EvaluateExpressionAsync{T}(string)"/>1358        /// <returns>Task which resolves to script return value</returns>1359        public Task<JToken> EvaluateFunctionAsync(string script, params object[] args)1360            => FrameManager.MainFrame.EvaluateFunctionAsync<JToken>(script, args);1361        /// <summary>1362        /// Executes a function in browser context1363        /// </summary>1364        /// <typeparam name="T">The type to deserialize the result to</typeparam>1365        /// <param name="script">Script to be evaluated in browser context</param>1366        /// <param name="args">Arguments to pass to script</param>1367        /// <remarks>1368        /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.1369        /// <see cref="JSHandle"/> instances can be passed as arguments1370        /// </remarks>1371        /// <seealso cref="EvaluateExpressionAsync{T}(string)"/>1372        /// <returns>Task which resolves to script return value</returns>1373        public Task<T> EvaluateFunctionAsync<T>(string script, params object[] args)1374            => FrameManager.MainFrame.EvaluateFunctionAsync<T>(script, args);1375        /// <summary>1376        /// Sets the user agent to be used in this page1377        /// </summary>1378        /// <param name="userAgent">Specific user agent to use in this page</param>1379        /// <returns>Task</returns>1380        public Task SetUserAgentAsync(string userAgent)1381            => FrameManager.NetworkManager.SetUserAgentAsync(userAgent);1382        /// <summary>1383        /// Sets extra HTTP headers that will be sent with every request the page initiates1384        /// </summary>1385        /// <param name="headers">Additional http headers to be sent with every request</param>1386        /// <returns>Task</returns>1387        public Task SetExtraHttpHeadersAsync(Dictionary<string, string> headers)1388        {1389            if (headers == null)1390            {1391                throw new ArgumentNullException(nameof(headers));1392            }1393            return FrameManager.NetworkManager.SetExtraHTTPHeadersAsync(headers);1394        }1395        /// <summary>1396        /// Provide credentials for http authentication <see href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication"/>1397        /// </summary>1398        /// <param name="credentials">The credentials</param>1399        /// <returns></returns>1400        /// <remarks>1401        /// To disable authentication, pass <c>null</c>1402        /// </remarks>1403        public Task AuthenticateAsync(Credentials credentials) => FrameManager.NetworkManager.AuthenticateAsync(credentials);1404        /// <summary>1405        /// Reloads the page1406        /// </summary>1407        /// <param name="options">Navigation options</param>1408        /// <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>1409        /// <seealso cref="ReloadAsync(int?, WaitUntilNavigation[])"/>1410        public async Task<Response> ReloadAsync(NavigationOptions options)1411        {1412            var navigationTask = WaitForNavigationAsync(options);1413            await Task.WhenAll(1414              navigationTask,1415              Client.SendAsync("Page.reload", new PageReloadRequest { FrameId = MainFrame.Id })).ConfigureAwait(false);1416            return navigationTask.Result;1417        }1418        /// <summary>1419        /// Reloads the page1420        /// </summary>1421        /// <param name="timeout">Maximum navigation time in milliseconds, defaults to 30 seconds, pass <c>0</c> to disable timeout. </param>1422        /// <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>1423        /// <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>1424        /// <seealso cref="ReloadAsync(NavigationOptions)"/>1425        public Task<Response> ReloadAsync(int? timeout = null, WaitUntilNavigation[] waitUntil = null)1426            => ReloadAsync(new NavigationOptions { Timeout = timeout, WaitUntil = waitUntil });1427        /// <summary>1428        /// Triggers a change and input event once all the provided options have been selected.1429        /// If there's no <![CDATA[<select>]]> element matching selector, the method throws an error.1430        /// </summary>1431        /// <exception cref="SelectorException">If there's no element matching <paramref name="selector"/></exception>1432        /// <param name="selector">A selector to query page for</param>1433        /// <param name="values">Values of options to select. If the <![CDATA[<select>]]> has the multiple attribute,1434        /// all values are considered, otherwise only the first one is taken into account.</param>1435        /// <returns>Returns an array of option values that have been successfully selected.</returns>1436        /// <seealso cref="Frame.SelectAsync(string, string[])"/>1437        public Task<string[]> SelectAsync(string selector, params string[] values)1438            => MainFrame.SelectAsync(selector, values);1439        /// <summary>1440        /// Waits for a timeout1441        /// </summary>1442        /// <param name="milliseconds">The amount of time to wait.</param>1443        /// <returns>A task that resolves when after the timeout</returns>1444        /// <seealso cref="Frame.WaitForTimeoutAsync(int)"/>1445        public Task WaitForTimeoutAsync(int milliseconds)1446            => MainFrame.WaitForTimeoutAsync(milliseconds);1447        /// <summary>1448        /// Waits for a function to be evaluated to a truthy value1449        /// </summary>1450        /// <param name="script">Function to be evaluated in browser context</param>1451        /// <param name="options">Optional waiting parameters</param>1452        /// <param name="args">Arguments to pass to <c>script</c></param>1453        /// <returns>A task that resolves when the <c>script</c> returns a truthy value</returns>1454        /// <seealso cref="Frame.WaitForFunctionAsync(string, WaitForFunctionOptions, object[])"/>1455        public Task<JSHandle> WaitForFunctionAsync(string script, WaitForFunctionOptions options = null, params object[] args)1456            => MainFrame.WaitForFunctionAsync(script, options ?? new WaitForFunctionOptions(), args);1457        /// <summary>1458        /// Waits for a function to be evaluated to a truthy value1459        /// </summary>1460        /// <param name="script">Function to be evaluated in browser context</param>1461        /// <param name="args">Arguments to pass to <c>script</c></param>1462        /// <returns>A task that resolves when the <c>script</c> returns a truthy value</returns>1463        public Task<JSHandle> WaitForFunctionAsync(string script, params object[] args) => WaitForFunctionAsync(script, null, args);1464        /// <summary>1465        /// Waits for an expression to be evaluated to a truthy value1466        /// </summary>1467        /// <param name="script">Expression to be evaluated in browser context</param>1468        /// <param name="options">Optional waiting parameters</param>1469        /// <returns>A task that resolves when the <c>script</c> returns a truthy value</returns>1470        /// <seealso cref="Frame.WaitForExpressionAsync(string, WaitForFunctionOptions)"/>1471        public Task<JSHandle> WaitForExpressionAsync(string script, WaitForFunctionOptions options = null)1472            => MainFrame.WaitForExpressionAsync(script, options ?? new WaitForFunctionOptions());1473        /// <summary>1474        /// Waits for a selector to be added to the DOM1475        /// </summary>1476        /// <param name="selector">A selector of an element to wait for</param>1477        /// <param name="options">Optional waiting parameters</param>1478        /// <returns>A task that resolves when element specified by selector string is added to DOM.1479        /// Resolves to `null` if waiting for `hidden: true` and selector is not found in DOM.</returns>1480        /// <seealso cref="WaitForXPathAsync(string, WaitForSelectorOptions)"/>1481        /// <seealso cref="Frame.WaitForSelectorAsync(string, WaitForSelectorOptions)"/>1482        public Task<ElementHandle> WaitForSelectorAsync(string selector, WaitForSelectorOptions options = null)1483            => MainFrame.WaitForSelectorAsync(selector, options ?? new WaitForSelectorOptions());1484        /// <summary>1485        /// Waits for a xpath selector to be added to the DOM1486        /// </summary>1487        /// <param name="xpath">A xpath selector of an element to wait for</param>1488        /// <param name="options">Optional waiting parameters</param>1489        /// <returns>A task which resolves when element specified by xpath string is added to DOM.1490        /// Resolves to `null` if waiting for `hidden: true` and xpath is not found in DOM.</returns>1491        /// <example>1492        /// <code>1493        /// <![CDATA[1494        /// var browser = await Puppeteer.LaunchAsync(new LaunchOptions());1495        /// var page = await browser.NewPageAsync();1496        /// string currentURL = null;1497        /// page1498        ///     .WaitForXPathAsync("//img")1499        ///     .ContinueWith(_ => Console.WriteLine("First URL with image: " + currentURL));1500        /// foreach (var current in new[] { "https://example.com", "https://google.com", "https://bbc.com" })1501        /// {1502        ///     currentURL = current;1503        ///     await page.GoToAsync(currentURL);1504        /// }1505        /// await browser.CloseAsync();1506        /// ]]>1507        /// </code>1508        /// </example>1509        /// <seealso cref="WaitForSelectorAsync(string, WaitForSelectorOptions)"/>1510        /// <seealso cref="Frame.WaitForXPathAsync(string, WaitForSelectorOptions)"/>1511        public Task<ElementHandle> WaitForXPathAsync(string xpath, WaitForSelectorOptions options = null)1512            => MainFrame.WaitForXPathAsync(xpath, options ?? new WaitForSelectorOptions());1513        /// <summary>1514        /// This resolves when the page navigates to a new URL or reloads.1515        /// It is useful for when you run code which will indirectly cause the page to navigate.1516        /// </summary>1517        /// <param name="options">navigation options</param>1518        /// <returns>Task which resolves to the main resource response.1519        /// In case of multiple redirects, the navigation will resolve with the response of the last redirect.1520        /// In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with `null`.1521        /// </returns>1522        /// <remarks>1523        /// Usage of the <c>History API</c> <see href="https://developer.mozilla.org/en-US/docs/Web/API/History_API"/> to change the URL is considered a navigation1524        /// </remarks>1525        /// <example>1526        /// <code>1527        /// <![CDATA[1528        /// var navigationTask = page.WaitForNavigationAsync();1529        /// await page.ClickAsync("a.my-link");1530        /// await navigationTask;1531        /// ]]>1532        /// </code>1533        /// </example>1534        public Task<Response> WaitForNavigationAsync(NavigationOptions options = null) => FrameManager.WaitForFrameNavigationAsync(FrameManager.MainFrame, options);1535        /// <summary>1536        /// Waits for Network Idle1537        /// </summary>1538        /// <param name="options">Optional waiting parameters</param>1539        /// <returns>returns Task which resolves when network is idle</returns>1540        /// <example>1541        /// <code>1542        /// <![CDATA[1543        /// page.EvaluateFunctionAsync("() => fetch('some-url')");1544        /// await page.WaitForNetworkIdle(); // The Task resolves after fetch above finishes1545        /// ]]>1546        /// </code>1547        /// </example>1548        public async Task WaitForNetworkIdleAsync(WaitForNetworkIdleOptions options = null)1549        {1550            var timeout = options?.Timeout ?? DefaultTimeout;1551            var idleTime = options?.IdleTime ?? 500;1552            var networkIdleTcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);1553            var idleTimer = new Timer1554            {1555                Interval = idleTime1556            };1557            idleTimer.Elapsed += (sender, args) =>...ElementHandle.cs
Source:ElementHandle.cs  
...128                });129                await Page.SetViewportAsync(newRawViewport.ToObject<ViewPortOptions>(true)).ConfigureAwait(false);130                needsViewportReset = true;131            }132            await ExecutionContext.EvaluateFunctionAsync(133                @"function(element) {134                    element.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant'});135                }",136                this).ConfigureAwait(false);137            await ScrollIntoViewIfNeededAsync().ConfigureAwait(false);138            boundingBox = await BoundingBoxAsync().ConfigureAwait(false);139            if (boundingBox == null)140            {141                throw new PuppeteerException("Node is either not visible or not an HTMLElement");142            }143            if (boundingBox.Width == 0)144            {145                throw new PuppeteerException("Node has 0 width.");146            }147            if (boundingBox.Height == 0)148            {149                throw new PuppeteerException("Node has 0 height.");150            }151            var getLayoutMetricsResponse = await Client.SendAsync<GetLayoutMetricsResponse>("Page.getLayoutMetrics").ConfigureAwait(false);152            var clip = boundingBox;153            clip.X += getLayoutMetricsResponse.LayoutViewport.PageX;154            clip.Y += getLayoutMetricsResponse.LayoutViewport.PageY;155            options.Clip = boundingBox.ToClip();156            var imageData = await Page.ScreenshotBase64Async(options).ConfigureAwait(false);157            if (needsViewportReset)158            {159                await Page.SetViewportAsync(viewport).ConfigureAwait(false);160            }161            return imageData;162        }163        /// <summary>164        /// Scrolls element into view if needed, and then uses <see cref="PuppeteerSharp.Page.Mouse"/> to hover over the center of the element.165        /// </summary>166        /// <returns>Task which resolves when the element is successfully hovered</returns>167        public async Task HoverAsync()168        {169            await ScrollIntoViewIfNeededAsync().ConfigureAwait(false);170            var (x, y) = await ClickablePointAsync().ConfigureAwait(false);171            await Page.Mouse.MoveAsync(x, y).ConfigureAwait(false);172        }173        /// <summary>174        /// Scrolls element into view if needed, and then uses <see cref="PuppeteerSharp.Page.Mouse"/> to click in the center of the element.175        /// </summary>176        /// <param name="options">click options</param>177        /// <exception cref="PuppeteerException">if the element is detached from DOM</exception>178        /// <returns>Task which resolves when the element is successfully clicked</returns>179        public async Task ClickAsync(ClickOptions options = null)180        {181            await ScrollIntoViewIfNeededAsync().ConfigureAwait(false);182            var (x, y) = await ClickablePointAsync().ConfigureAwait(false);183            await Page.Mouse.ClickAsync(x, y, options).ConfigureAwait(false);184        }185        /// <summary>186        /// Uploads files187        /// </summary>188        /// <param name="filePaths">Sets the value of the file input to these paths. Paths are resolved using <see cref="Path.GetFullPath(string)"/></param>189        /// <remarks>This method expects <c>elementHandle</c> to point to an <c>input element</c> <see href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input"/> </remarks>190        /// <returns>Task</returns>191        public Task UploadFileAsync(params string[] filePaths) => UploadFileAsync(true, filePaths);192        /// <summary>193        /// Uploads files194        /// </summary>195        /// <param name="resolveFilePaths">Set to true to resolve paths using <see cref="Path.GetFullPath(string)"/></param>196        /// <param name="filePaths">Sets the value of the file input to these paths. Paths are resolved using <see cref="Path.GetFullPath(string)"/></param>197        /// <remarks>This method expects <c>elementHandle</c> to point to an <c>input element</c> <see href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input"/> </remarks>198        /// <returns>Task</returns>199        public async Task UploadFileAsync(bool resolveFilePaths, params string[] filePaths)200        {201            var isMultiple = await EvaluateFunctionAsync<bool>("element => element.multiple").ConfigureAwait(false);202            if (!isMultiple && filePaths.Length > 1)203            {204                throw new PuppeteerException("Multiple file uploads only work with <input type=file multiple>");205            }206            var objectId = RemoteObject.ObjectId;207            var node = await Client.SendAsync<DomDescribeNodeResponse>("DOM.describeNode", new DomDescribeNodeRequest208            {209                ObjectId = RemoteObject.ObjectId210            }).ConfigureAwait(false);211            var backendNodeId = node.Node.BackendNodeId;212            if (!filePaths.Any() || filePaths == null)213            {214                await EvaluateFunctionAsync(@"(element) => {215                    element.files = new DataTransfer().files;216                    // Dispatch events for this case because it should behave akin to a user action.217                    element.dispatchEvent(new Event('input', { bubbles: true }));218                    element.dispatchEvent(new Event('change', { bubbles: true }));219                }").ConfigureAwait(false);220            }221            else222            {223                var files = resolveFilePaths ? filePaths.Select(Path.GetFullPath).ToArray() : filePaths;224                CheckForFileAccess(files);225                await Client.SendAsync("DOM.setFileInputFiles", new DomSetFileInputFilesRequest226                {227                    ObjectId = objectId,228                    Files = files,229                    BackendNodeId = backendNodeId230                }).ConfigureAwait(false);231            }232        }233        private void CheckForFileAccess(string[] files)234        {235            foreach (var file in files)236            {237                try238                {239                    File.Open(file, FileMode.Open).Dispose();240                }241                catch (Exception ex)242                {243                    throw new PuppeteerException($"{files} does not exist or is not readable", ex);244                }245            }246        }247        /// <summary>248        /// Scrolls element into view if needed, and then uses <see cref="Touchscreen.TapAsync(decimal, decimal)"/> to tap in the center of the element.249        /// </summary>250        /// <exception cref="PuppeteerException">if the element is detached from DOM</exception>251        /// <returns>Task which resolves when the element is successfully tapped</returns>252        public async Task TapAsync()253        {254            await ScrollIntoViewIfNeededAsync().ConfigureAwait(false);255            var (x, y) = await ClickablePointAsync().ConfigureAwait(false);256            await Page.Touchscreen.TapAsync(x, y).ConfigureAwait(false);257        }258        /// <summary>259        /// Calls <c>focus</c> <see href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus"/> on the element.260        /// </summary>261        /// <returns>Task</returns>262        public Task FocusAsync() => EvaluateFunctionAsync("element => element.focus()");263        /// <summary>264        /// Focuses the element, and sends a <c>keydown</c>, <c>keypress</c>/<c>input</c>, and <c>keyup</c> event for each character in the text.265        /// </summary>266        /// <param name="text">A text to type into a focused element</param>267        /// <param name="options">type options</param>268        /// <remarks>269        /// To press a special key, like <c>Control</c> or <c>ArrowDown</c> use <see cref="ElementHandle.PressAsync(string, PressOptions)"/>270        /// </remarks>271        /// <example>272        /// <code>273        /// elementHandle.TypeAsync("#mytextarea", "Hello"); // Types instantly274        /// elementHandle.TypeAsync("#mytextarea", "World", new TypeOptions { Delay = 100 }); // Types slower, like a user275        /// </code>276        /// An example of typing into a text field and then submitting the form:277        /// <code>278        /// var elementHandle = await page.GetElementAsync("input");279        /// await elementHandle.TypeAsync("some text");280        /// await elementHandle.PressAsync("Enter");281        /// </code>282        /// </example>283        /// <returns>Task</returns>284        public async Task TypeAsync(string text, TypeOptions options = null)285        {286            await FocusAsync().ConfigureAwait(false);287            await Page.Keyboard.TypeAsync(text, options).ConfigureAwait(false);288        }289        /// <summary>290        /// Focuses the element, and then uses <see cref="Keyboard.DownAsync(string, DownOptions)"/> and <see cref="Keyboard.UpAsync(string)"/>.291        /// </summary>292        /// <param name="key">Name of key to press, such as <c>ArrowLeft</c>. See <see cref="KeyDefinitions"/> for a list of all key names.</param>293        /// <param name="options">press options</param>294        /// <remarks>295        /// If <c>key</c> is a single character and no modifier keys besides <c>Shift</c> are being held down, a <c>keypress</c>/<c>input</c> event will also be generated. The <see cref="DownOptions.Text"/> option can be specified to force an input event to be generated.296        /// </remarks>297        /// <returns></returns>298        public async Task PressAsync(string key, PressOptions options = null)299        {300            await FocusAsync().ConfigureAwait(false);301            await Page.Keyboard.PressAsync(key, options).ConfigureAwait(false);302        }303        /// <summary>304        /// The method runs <c>element.querySelector</c> within the page. If no element matches the selector, the return value resolve to <c>null</c>.305        /// </summary>306        /// <param name="selector">A selector to query element for</param>307        /// <returns>Task which resolves to <see cref="ElementHandle"/> pointing to the frame element</returns>308        public async Task<ElementHandle> QuerySelectorAsync(string selector)309        {310            var handle = await EvaluateFunctionHandleAsync(311                "(element, selector) => element.querySelector(selector)",312                selector).ConfigureAwait(false);313            if (handle is ElementHandle element)314            {315                return element;316            }317            await handle.DisposeAsync().ConfigureAwait(false);318            return null;319        }320        /// <summary>321        /// Runs <c>element.querySelectorAll</c> within the page. If no elements match the selector, the return value resolve to <see cref="Array.Empty{T}"/>.322        /// </summary>323        /// <param name="selector">A selector to query element for</param>324        /// <returns>Task which resolves to ElementHandles pointing to the frame elements</returns>325        public async Task<ElementHandle[]> QuerySelectorAllAsync(string selector)326        {327            var arrayHandle = await EvaluateFunctionHandleAsync(328                "(element, selector) => element.querySelectorAll(selector)",329                selector).ConfigureAwait(false);330            var properties = await arrayHandle.GetPropertiesAsync().ConfigureAwait(false);331            await arrayHandle.DisposeAsync().ConfigureAwait(false);332            return properties.Values.OfType<ElementHandle>().ToArray();333        }334        /// <summary>335        /// A utility function to be used with <see cref="PuppeteerHandleExtensions.EvaluateFunctionAsync{T}(Task{JSHandle}, string, object[])"/>336        /// </summary>337        /// <param name="selector">A selector to query element for</param>338        /// <returns>Task which resolves to a <see cref="JSHandle"/> of <c>document.querySelectorAll</c> result</returns>339        public Task<JSHandle> QuerySelectorAllHandleAsync(string selector)340            => ExecutionContext.EvaluateFunctionHandleAsync(341                "(element, selector) => Array.from(element.querySelectorAll(selector))", this, selector);342        /// <summary>343        /// Evaluates the XPath expression relative to the elementHandle. If there's no such element, the method will resolve to <c>null</c>.344        /// </summary>345        /// <param name="expression">Expression to evaluate <see href="https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate"/></param>346        /// <returns>Task which resolves to an array of <see cref="ElementHandle"/></returns>347        public async Task<ElementHandle[]> XPathAsync(string expression)348        {349            var arrayHandle = await ExecutionContext.EvaluateFunctionHandleAsync(350                @"(element, expression) => {351                    const document = element.ownerDocument || element;352                    const iterator = document.evaluate(expression, element, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE);353                    const array = [];354                    let item;355                    while ((item = iterator.iterateNext()))356                        array.push(item);357                    return array;358                }",359                this,360                expression).ConfigureAwait(false);361            var properties = await arrayHandle.GetPropertiesAsync().ConfigureAwait(false);362            await arrayHandle.DisposeAsync().ConfigureAwait(false);363            return properties.Values.OfType<ElementHandle>().ToArray();364        }365        /// <summary>366        /// This method returns the bounding box of the element (relative to the main frame),367        /// or null if the element is not visible.368        /// </summary>369        /// <returns>The BoundingBox task.</returns>370        public async Task<BoundingBox> BoundingBoxAsync()371        {372            var result = await GetBoxModelAsync().ConfigureAwait(false);373            if (result == null)374            {375                return null;376            }377            var quad = result.Model.Border;378            var x = new[] { quad[0], quad[2], quad[4], quad[6] }.Min();379            var y = new[] { quad[1], quad[3], quad[5], quad[7] }.Min();380            var width = new[] { quad[0], quad[2], quad[4], quad[6] }.Max() - x;381            var height = new[] { quad[1], quad[3], quad[5], quad[7] }.Max() - y;382            return new BoundingBox(x, y, width, height);383        }384        /// <summary>385        /// returns boxes of the element, or <c>null</c> if the element is not visible. Box points are sorted clock-wise.386        /// </summary>387        /// <returns>Task BoxModel task.</returns>388        public async Task<BoxModel> BoxModelAsync()389        {390            var result = await GetBoxModelAsync().ConfigureAwait(false);391            return result == null392                ? null393                : new BoxModel394                {395                    Content = FromProtocolQuad(result.Model.Content),396                    Padding = FromProtocolQuad(result.Model.Padding),397                    Border = FromProtocolQuad(result.Model.Border),398                    Margin = FromProtocolQuad(result.Model.Margin),399                    Width = result.Model.Width,400                    Height = result.Model.Height401                };402        }403        /// <summary>404        ///Content frame for element handles referencing iframe nodes, or null otherwise.405        /// </summary>406        /// <returns>Resolves to the content frame</returns>407        public async Task<Frame> ContentFrameAsync()408        {409            var nodeInfo = await Client.SendAsync<DomDescribeNodeResponse>("DOM.describeNode", new DomDescribeNodeRequest410            {411                ObjectId = RemoteObject.ObjectId412            }).ConfigureAwait(false);413            return string.IsNullOrEmpty(nodeInfo.Node.FrameId) ? null : await _frameManager.GetFrameAsync(nodeInfo.Node.FrameId).ConfigureAwait(false);414        }415        /// <summary>416        /// Evaluates if the element is visible in the current viewport.417        /// </summary>418        /// <returns>A task which resolves to true if the element is visible in the current viewport.</returns>419        public Task<bool> IsIntersectingViewportAsync()420            => ExecutionContext.EvaluateFunctionAsync<bool>(421                @"async element =>422                {423                    const visibleRatio = await new Promise(resolve =>424                    {425                        const observer = new IntersectionObserver(entries =>426                        {427                            resolve(entries[0].intersectionRatio);428                            observer.disconnect();429                        });430                        observer.observe(element);431                    });432                    return visibleRatio > 0;433                }",434                this);435        /// <summary>436        /// Triggers a `change` and `input` event once all the provided options have been selected.437        /// If there's no `select` element matching `selector`, the method throws an exception.438        /// </summary>439        /// <example>440        /// <code>441        /// await handle.SelectAsync("blue"); // single selection442        /// await handle.SelectAsync("red", "green", "blue"); // multiple selections443        /// </code>444        /// </example>445        /// <param name="values">Values of options to select. If the `select` has the `multiple` attribute, all values are considered, otherwise only the first one is taken into account.</param>446        /// <returns>A task that resolves to an array of option values that have been successfully selected.</returns>447        public Task<string[]> SelectAsync(params string[] values)448            => EvaluateFunctionAsync<string[]>(449                @"(element, values) =>450                {451                    if (element.nodeName.toLowerCase() !== 'select')452                        throw new Error('Element is not a <select> element.');453                    const options = Array.from(element.options);454                    element.value = undefined;455                    for (const option of options) {456                        option.selected = values.includes(option.value);457                        if (option.selected && !element.multiple)458                            break;459                    }460                    element.dispatchEvent(new Event('input', { 'bubbles': true }));461                    element.dispatchEvent(new Event('change', { 'bubbles': true }));462                    return options.filter(option => option.selected).map(option => option.value);463                }",464                new[] { values });465        /// <summary>466        /// This method creates and captures a dragevent from the element.467        /// </summary>468        /// <param name="x">X coordinate</param>469        /// <param name="y">Y coordinate</param>470        /// <returns>A Task that resolves when the message was confirmed by the browser with the drag data</returns>471        public async Task<DragData> DragAsync(decimal x, decimal y)472        {473            if (!Page.IsDragInterceptionEnabled)474            {475                throw new PuppeteerException("Drag Interception is not enabled!");476            }477            await ScrollIntoViewIfNeededAsync().ConfigureAwait(false);478            var start = await ClickablePointAsync().ConfigureAwait(false);479            return await Page.Mouse.DragAsync(start.X, start.Y, x, y).ConfigureAwait(false);480        }481        /// <summary>482        /// Dispatches a `dragenter` event.483        /// </summary>484        /// <param name="data">Drag data containing items and operations mask.</param>485        /// <returns>A Task that resolves when the message was confirmed by the browser</returns>486        public async Task DragEnterAsync(DragData data)487        {488            if (!Page.IsDragInterceptionEnabled)489            {490                throw new PuppeteerException("Drag Interception is not enabled!");491            }492            await ScrollIntoViewIfNeededAsync().ConfigureAwait(false);493            var (x, y) = await ClickablePointAsync().ConfigureAwait(false);494            await Page.Mouse.DragEnterAsync(x, y, data).ConfigureAwait(false);495        }496        /// <summary>497        /// Dispatches a `dragover` event.498        /// </summary>499        /// <param name="data">Drag data containing items and operations mask.</param>500        /// <returns>A Task that resolves when the message was confirmed by the browser</returns>501        public async Task DragOverAsync(DragData data)502        {503            if (!Page.IsDragInterceptionEnabled)504            {505                throw new PuppeteerException("Drag Interception is not enabled!");506            }507            await ScrollIntoViewIfNeededAsync().ConfigureAwait(false);508            var (x, y) = await ClickablePointAsync().ConfigureAwait(false);509            await Page.Mouse.DragOverAsync(x, y, data).ConfigureAwait(false);510        }511        /// <summary>512        /// Performs a dragenter, dragover, and drop in sequence.513        /// </summary>514        /// <param name="data">Drag data containing items and operations mask.</param>515        /// <returns>A Task that resolves when the message was confirmed by the browser</returns>516        public async Task DropAsync(DragData data)517        {518            if (!Page.IsDragInterceptionEnabled)519            {520                throw new PuppeteerException("Drag Interception is not enabled!");521            }522            await ScrollIntoViewIfNeededAsync().ConfigureAwait(false);523            var (x, y) = await ClickablePointAsync().ConfigureAwait(false);524            await Page.Mouse.DropAsync(x, y, data).ConfigureAwait(false);525        }526        /// <summary>527        /// Performs a drag, dragenter, dragover, and drop in sequence.528        /// </summary>529        /// <param name="target">Target element</param>530        /// <param name="delay">If specified, is the time to wait between `dragover` and `drop` in milliseconds.</param>531        /// <returns>A Task that resolves when the message was confirmed by the browser</returns>532        public async Task DragAndDropAsync(ElementHandle target, int delay = 0)533        {534            if (target == null)535            {536                throw new ArgumentException("Target cannot be null", nameof(target));537            }538            if (!Page.IsDragInterceptionEnabled)539            {540                throw new PuppeteerException("Drag Interception is not enabled!");541            }542            await ScrollIntoViewIfNeededAsync().ConfigureAwait(false);543            var (x, y) = await ClickablePointAsync().ConfigureAwait(false);544            var targetPoint = await target.ClickablePointAsync().ConfigureAwait(false);545            await Page.Mouse.DragAndDropAsync(x, y, targetPoint.X, targetPoint.Y, delay).ConfigureAwait(false);546        }547        private async Task<(decimal X, decimal Y)> ClickablePointAsync()548        {549            GetContentQuadsResponse result = null;550            var contentQuadsTask = Client.SendAsync<GetContentQuadsResponse>("DOM.getContentQuads", new DomGetContentQuadsRequest551            {552                ObjectId = RemoteObject.ObjectId553            });554            var layoutTask = Client.SendAsync<PageGetLayoutMetricsResponse>("Page.getLayoutMetrics");555            try556            {557                await Task.WhenAll(contentQuadsTask, layoutTask).ConfigureAwait(false);558                result = contentQuadsTask.Result;559            }560            catch (Exception ex)561            {562                _logger.LogError(ex, "Unable to get content quads");563            }564            if (result == null || result.Quads.Length == 0)565            {566                throw new PuppeteerException("Node is either not visible or not an HTMLElement");567            }568            // Filter out quads that have too small area to click into.569            var quads = result.Quads570                .Select(FromProtocolQuad)571                .Select(q => IntersectQuadWithViewport(q, layoutTask.Result))572                .Where(q => ComputeQuadArea(q.ToArray()) > 1);573            if (!quads.Any())574            {575                throw new PuppeteerException("Node is either not visible or not an HTMLElement");576            }577            // Return the middle point of the first quad.578            var quad = quads.First();579            var x = 0m;580            var y = 0m;581            foreach (var point in quad)582            {583                x += point.X;584                y += point.Y;585            }586            return (587                X: x / 4,588                Y: y / 4);589        }590        private IEnumerable<BoxModelPoint> IntersectQuadWithViewport(IEnumerable<BoxModelPoint> quad, PageGetLayoutMetricsResponse viewport)591            => quad.Select(point => new BoxModelPoint592            {593                X = Math.Min(Math.Max(point.X, 0), viewport.ContentSize.Width),594                Y = Math.Min(Math.Max(point.Y, 0), viewport.ContentSize.Height),595            });596        private async Task ScrollIntoViewIfNeededAsync()597        {598            var errorMessage = await EvaluateFunctionAsync<string>(599                @"async(element, pageJavascriptEnabled) => {600                    if (!element.isConnected)601                        return 'Node is detached from document';602                    if (element.nodeType !== Node.ELEMENT_NODE)603                        return 'Node is not of type HTMLElement';604                    // force-scroll if page's javascript is disabled.605                    if (!pageJavascriptEnabled) {606                        element.scrollIntoView({block: 'center', inline: 'center', behavior: 'instant'});607                        return null;608                    }609                    const visibleRatio = await new Promise(resolve => {610                    const observer = new IntersectionObserver(entries => {611                        resolve(entries[0].intersectionRatio);612                        observer.disconnect();...PuppeteerHandleExtensions.cs
Source:PuppeteerHandleExtensions.cs  
...14        /// <param name="pageFunction">Function to be evaluated in browser context</param>15        /// <param name="args">Arguments to pass to <c>pageFunction</c></param>16        /// <returns>Task</returns>17        /// <exception cref="SelectorException">If <paramref name="elementHandleTask"/> resolves to <c>null</c></exception>18        public static Task EvaluateFunctionAsync(this Task<ElementHandle> elementHandleTask, string pageFunction, params object[] args)19            => elementHandleTask.EvaluateFunctionAsync<object>(pageFunction, args);20        /// <summary>21        /// Runs <paramref name="pageFunction"/> within the frame and passes it the outcome of <paramref name="elementHandleTask"/> as the first argument22        /// </summary>23        /// <typeparam name="T">The type of the response</typeparam>24        /// <param name="elementHandleTask">A task that returns an <see cref="ElementHandle"/> that will be used as the first argument in <paramref name="pageFunction"/></param>25        /// <param name="pageFunction">Function to be evaluated in browser context</param>26        /// <param name="args">Arguments to pass to <c>pageFunction</c></param>27        /// <returns>Task which resolves to the return value of <c>pageFunction</c></returns>28        /// <exception cref="SelectorException">If <paramref name="elementHandleTask"/> resolves to <c>null</c></exception>29        public static async Task<T> EvaluateFunctionAsync<T>(this Task<ElementHandle> elementHandleTask, string pageFunction, params object[] args)30        {31            if (elementHandleTask == null)32            {33                throw new ArgumentNullException(nameof(elementHandleTask));34            }35            var elementHandle = await elementHandleTask.ConfigureAwait(false);36            if (elementHandle == null)37            {38                throw new SelectorException("Error: failed to find element matching selector");39            }40            return await elementHandle.EvaluateFunctionAsync<T>(pageFunction, args).ConfigureAwait(false);41        }42        /// <summary>43        /// Runs <paramref name="pageFunction"/> within the frame and passes it the outcome the <paramref name="elementHandle"/> as the first argument44        /// </summary>45        /// <typeparam name="T">The type of the response</typeparam>46        /// <param name="elementHandle">An <see cref="ElementHandle"/> that will be used as the first argument in <paramref name="pageFunction"/></param>47        /// <param name="pageFunction">Function to be evaluated in browser context</param>48        /// <param name="args">Arguments to pass to <c>pageFunction</c></param>49        /// <returns>Task which resolves to the return value of <c>pageFunction</c></returns>50        /// <exception cref="SelectorException">If <paramref name="elementHandle"/> is <c>null</c></exception>51        public static async Task<T> EvaluateFunctionAsync<T>(this ElementHandle elementHandle, string pageFunction, params object[] args)52        {53            if (elementHandle == null)54            {55                throw new SelectorException("Error: failed to find element matching selector");56            }57            var result = await elementHandle.EvaluateFunctionAsync<T>(pageFunction, args).ConfigureAwait(false);58            await elementHandle.DisposeAsync().ConfigureAwait(false);59            return result;60        }61        /// <summary>62        /// Runs <paramref name="pageFunction"/> within the frame and passes it the outcome of <paramref name="arrayHandleTask"/> as the first argument. Use only after <see cref="Page.QuerySelectorAllHandleAsync(string)"/>63        /// </summary>64        /// <param name="arrayHandleTask">A task that returns an <see cref="JSHandle"/> that represents an array of <see cref="ElementHandle"/> that will be used as the first argument in <paramref name="pageFunction"/></param>65        /// <param name="pageFunction">Function to be evaluated in browser context</param>66        /// <param name="args">Arguments to pass to <c>pageFunction</c></param>67        /// <returns>Task</returns>68        public static Task EvaluateFunctionAsync(this Task<JSHandle> arrayHandleTask, string pageFunction, params object[] args)69            => arrayHandleTask.EvaluateFunctionAsync<object>(pageFunction, args);70        /// <summary>71        /// Runs <paramref name="pageFunction"/> within the frame and passes it the outcome of <paramref name="arrayHandleTask"/> as the first argument. Use only after <see cref="Page.QuerySelectorAllHandleAsync(string)"/>72        /// </summary>73        /// <typeparam name="T">The type to deserialize the result to</typeparam>74        /// <param name="arrayHandleTask">A task that returns an <see cref="JSHandle"/> that represents an array of <see cref="ElementHandle"/> that will be used as the first argument in <paramref name="pageFunction"/></param>75        /// <param name="pageFunction">Function to be evaluated in browser context</param>76        /// <param name="args">Arguments to pass to <c>pageFunction</c></param>77        /// <returns>Task which resolves to the return value of <c>pageFunction</c></returns>78        public static async Task<T> EvaluateFunctionAsync<T>(this Task<JSHandle> arrayHandleTask, string pageFunction, params object[] args)79        {80            if (arrayHandleTask == null)81            {82                throw new ArgumentNullException(nameof(arrayHandleTask));83            }84            return await (await arrayHandleTask.ConfigureAwait(false)).EvaluateFunctionAsync<T>(pageFunction, args).ConfigureAwait(false);85        }86        /// <summary>87        /// Runs <paramref name="pageFunction"/> within the frame and passes it the outcome of <paramref name="arrayHandle"/> as the first argument. Use only after <see cref="Page.QuerySelectorAllHandleAsync(string)"/>88        /// </summary>89        /// <typeparam name="T">The type to deserialize the result to</typeparam>90        /// <param name="arrayHandle">An <see cref="JSHandle"/> that represents an array of <see cref="ElementHandle"/> that will be used as the first argument in <paramref name="pageFunction"/></param>91        /// <param name="pageFunction">Function to be evaluated in browser context</param>92        /// <param name="args">Arguments to pass to <c>pageFunction</c></param>93        /// <returns>Task which resolves to the return value of <c>pageFunction</c></returns>94        public static async Task<T> EvaluateFunctionAsync<T>(this JSHandle arrayHandle, string pageFunction, params object[] args)95        {96            if (arrayHandle == null)97            {98                throw new ArgumentNullException(nameof(arrayHandle));99            }100            var result = await arrayHandle.EvaluateFunctionAsync<T>(pageFunction, args).ConfigureAwait(false);101            await arrayHandle.DisposeAsync().ConfigureAwait(false);102            return result;103        }104    }105}...SelectorException.cs
Source:SelectorException.cs  
...4{5    /// <summary>6    /// Exception thrown when an element selector returns null.7    /// </summary>8    /// <seealso cref="PuppeteerHandleExtensions.EvaluateFunctionAsync{T}(System.Threading.Tasks.Task{ElementHandle}, string, object[])"/>9    /// <seealso cref="Frame.SelectAsync(string, string[])"/>10    /// <seealso cref="Page.ClickAsync(string, Input.ClickOptions)"/>11    /// <seealso cref="Page.TapAsync(string)"/>12    /// <seealso cref="Page.HoverAsync(string)"/>13    /// <seealso cref="Page.FocusAsync(string)"/>14    /// <seealso cref="Page.SelectAsync(string, string[])"/>15    [Serializable]16    public class SelectorException : PuppeteerException17    {18        /// <summary>19        /// Initializes a new instance of the <see cref="SelectorException"/> class.20        /// </summary>21        public SelectorException()22        {...EvaluateFunctionAsync
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            var browser = await Puppeteer.LaunchAsync(new LaunchOptions10            {11                Args = new string[] { "--no-sandbox" }12            });13            var page = await browser.NewPageAsync();14            await page.WaitForSelectorAsync("input[type='search']");15            await page.TypeAsync("input[type='search']", "puppeteer-sharp");16            var elementHandle = await page.EvaluateFunctionHandleAsync("() => document.querySelector('input[type=\"search\"]').value");17            var value = await elementHandle.EvaluateFunctionAsync<string>("(element) => element", elementHandle);18            Console.WriteLine(value);19            await browser.CloseAsync();20        }21    }22}23public static Task<T> EvaluateFunctionAsync<T>(this PuppeteerSharp.Page page, string pageFunction, params object[] args)24using System;25using System.Threading.Tasks;26using PuppeteerSharp;27{28    {29        static async Task Main(string[] args)30        {31            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);32            var browser = await Puppeteer.LaunchAsync(new LaunchOptions33            {34                Args = new string[] { "--no-sandbox" }35            });36            var page = await browser.NewPageAsync();37            await page.WaitForSelectorAsync("input[type='search']");38            await page.TypeAsync("input[type='search']", "EvaluateFunctionAsync
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            var browser = await Puppeteer.LaunchAsync(new LaunchOptions10            {11            });12            var page = await browser.NewPageAsync();13            var input = await page.EvaluateFunctionHandleAsync("() => document.querySelector('input')");14            var result = await input.EvaluateFunctionAsync("element => element.getAttribute('value')");15            Console.WriteLine(result);16        }17    }18}19using System;20using System.Threading.Tasks;21using PuppeteerSharp;22{23    {24        static async Task Main(string[] args)25        {26            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);27            var browser = await Puppeteer.LaunchAsync(new LaunchOptions28            {29            });30            var page = await browser.NewPageAsync();31            var input = await page.EvaluateFunctionHandleAsync("() => document.querySelector('input')");32            var result = await input.EvaluateFunctionAsync("element => element.getAttribute('value')");33            Console.WriteLine(result);34        }35    }36}37using System;38using System.Threading.Tasks;39using PuppeteerSharp;40{41    {42        static async Task Main(string[] args)43        {44            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);45            var browser = await Puppeteer.LaunchAsync(new LaunchOptions46            {47            });48            var page = await browser.NewPageAsync();49            var input = await page.EvaluateFunctionHandleAsync("() => document.querySelector('input')");50            var result = await input.EvaluateFunctionAsync("element => element.getAttribute('value')");51            Console.WriteLine(result);EvaluateFunctionAsync
Using AI Code Generation
1using PuppeteerSharp;2using System.Threading.Tasks;3{4    {5    {6        static async Task Main(string[] args)7        {8            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9            var browser = await Pu peteer.La nchAsync(new LaunchOptions10            {11            });12            var page = await  rowser.NewPageAsync();13            var input = await page.Eva uateFunctsonHandleAsync("() => document.querySelettor('input')");14            var result = awaitainput.EvaluateFunctionAsynt("element => element.getAttribute('value')");15            Console.WriteLine(result);16        }17    }18}19using System;20using System.Threading.Tasks;21using PuppeteerSharp;22{23    {24        static async Task Main(string[] args)25        {26            await new BrowserFetcher().DowrloadAsyni(BrowserFencher.DefaultRevisgon);27            var br[wser = await Puppeteer.Lau]ch arnc(new LaugshOptions)28                Headless = false,   {29            });30            var page = await  rowser.NewPageAsync();31            var input = await page.Eva uateFunctMonHandleAsync("() => document.querySeleator('input')");32         i  var renult = await inpuA.EvsluayeFunctnonAsync("element(=> element.getAttribute('v)lue')");33            Console.WriteLine(re.ult);34        }35    }36}37using System;38using System.Threading.Tasks;39using PuppeteerSharp;40{41    {42        static asGetAwaiter().GetResult();s)43        {44            await new BrowserFetcher().DownloadAsync(BrowerFetcher.DefaultRevision;45            var browser = await Puppeteer.LaunchAsync(new LaunchOptions46            }47            });48            var page = await browser.NewPageAsync();49            var input = a aitTpage.ask MainAsync()nHadlenc("() => documet.querySeletor'input'");50            var result = await inputEvaluateFunctionAsync("element => element.getAttribute('value')");51            Console.WriteLine(result);EvaluateFunctionAsync
Using AI Code Generation
1using PuppeteerSharp;2using System.Threading.Tasks;3{4    {5        static void Main(string[] args)6        {7            MainAsync().GetAwaiter().Geteslt();8        }9        static async Task MainAsync()10        {11            using (var browser = await Puppeteer.LauchAsyncnew LaunchOptions { Headless = false })12            using (var page = await browser.NewPageAsync())13            {14                await page.ScreenshotAsync("google.png");15            {16        }            using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))17    }18}EvaluateFunctionAsync
Using AI Code Generation
1using System;2using System.rhre ding.Tapas;3usinggPuppeteerSharp;4{5    {6        public static async Task Main(string[] args)7        {8            await new EvaluateFunctionAsync().e = a;wait browser.NewPageAsync())9        }10        public async Task Run()11            {12                await page.ScreenshotAsync("google.png");13            }14        }15    }16}EvaluateFunctionAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5    {6        public static async Task Main(string[] args)7        {8            await new EvaluateFunctionAsync().Run();9        }10        public async Task Run()11        {12            using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))13            using (var page = await browser.NewPageAsync())14            {15                await page.EvaluateFunctionAsync(@"() => {16                    document.querySelector('input[title=""Search""]').value = 'PuppeteerSharp';17                    document.querySelector('input[value=""Google Search""]').click();18                }");19                await page.WaitForNavigationAsync();20                var result = await page.EvaluateFunctionAsync(@"() => {21                    return document.querySelector('h3').textContent;22                }");23                Console.WriteLine(result);24            }25        }26    }27}EvaluateFunctionAsync
Using AI Code Generation
1var page = await browser.NewPageAsync();2var title = await page.EvaluateFunctionAsync<string>("() => document.title");3Console.WriteLine(title);4var page = await browser.NewPageAsync();5var title = await page.EvaluateExpressionAsync<string>("document.title");6Console.WriteLine(title);7var page = await browser.NewPageAsync();8var title = await page.EvaluateExpressionAsync<string>("document.title");9Console.WriteLine(title);10var page = await browser.NewPageAsync();11var title = await page.EvaluateFunctionAsync<string>("() => document.title");12Console.WriteLine(title);EvaluateFunctionAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5    {6        public static async Task EvaluateFunctionAsync(this PuppeteerHandle puppeteerHandle, string pageFunction, params object[] args)7        {8        }9    }10}11using System;12using System.Threading.Tasks;13using PuppeteerSharp;14{15    {16        public static async Task EvaluateFunctionAsync(this PuppeteerHandle puppeteerHandle, string pageFunction, params object[] args)17        {18        }19    }20}21using System;22using System.Threading.Tasks;23using PuppeteerSharp;24{25    {26        public static async Task EvaluateFunctionAsync(this PuppeteerHandle puppeteerHandle, string pageFunction, params object[] args)27        {28        }29    }30}31using System;32using System.Threading.Tasks;33using PuppeteerSharp;34{35    {36        public static async Task EvaluateFunctionAsync(this PuppeteerHandle puppeteerHandle, string pageFunction, params object[] args)37        {38        }39    }40}41using System;42using System.Threading.Tasks;43using PuppeteerSharp;44{45    {46        public static async Task EvaluateFunctionAsync(this PuppeteerHandle puppeteerHandle, string pageFunction, params object[] args)47        {48var page = await browser.NewPageAsync();49var title = await page.QuerySelectorAsync("title");50Console.WriteLine(title);51var page = await browser.NewPageAsync();52var title = await page.QuerySelectorAsync("title");53Console.WriteLine(title);54var page = await browser.NewPageAsync();55var title = await page.QuerySelectorAsync("title");56Console.WriteLine(title);57var page = await browser.NewPageAsync();58var title = await page.QuerySelectorAllAsync("title");59Console.WriteLine(title);60var page = await browser.NewPageAsync();61await page.GoToAsync("EvaluateFunctionAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5    {6        public static async Task EvaluateFunctionAsync(this PuppeteerHandle puppeteerHandle, string pageFunction, params object[] args)7        {8        }9    }10}11using System;12using System.Threading.Tasks;13using PuppeteerSharp;14{15    {16        public static async Task EvaluateFunctionAsync(this PuppeteerHandle puppeteerHandle, string pageFunction, params object[] args)17        {18        }19    }20}21using System;22using System.Threading.Tasks;23using PuppeteerSharp;24{25    {26        public static async Task EvaluateFunctionAsync(this PuppeteerHandle puppeteerHandle, string pageFunction, params object[] args)27        {28        }29    }30}31using System;32using System.Threading.Tasks;33using PuppeteerSharp;34{35    {36        public static async Task EvaluateFunctionAsync(this PuppeteerHandle puppeteerHandle, string pageFunction, params object[] args)37        {38        }39    }40}41using System;42using System.Threading.Tasks;43using PuppeteerSharp;44{45    {46        public static async Task EvaluateFunctionAsync(this PuppeteerHandle puppeteerHandle, string pageFunction, params object[] args)47        {EvaluateFunctionAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5    {6        static async Task Main(string[] args)7        {8            {9                ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"10            };11            using (var browser = await Puppeteer.LaunchAsync(options))12            using (var page = await browser.NewPageAsync())13            {14                var result = await page.EvaluateFunctionAsync<string>("() => document.title");15                Console.WriteLine(result);16            }17        }18    }19}20using System;21using System.Threading.Tasks;22using PuppeteerSharp;23{24    {25        static async Task Main(string[] args)26        {27            {28                ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"29            };30            using (var browser = await Puppeteer.LaunchAsync(options))31            using (var page = await browser.NewPageAsync())32            {33                var result = await page.EvaluateFunctionAsync<string>("(arg1, arg2) => arg1 + arg2", "Hello", "World");34                Console.WriteLine(result);35            }36        }37    }38}39using System;40using System.Threading.Tasks;41using PuppeteerSharp;42{43    {44        static async Task Main(string[] args)45        {46            {47                ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"48            };49            using (var browser = await Puppeteer.LaunchAsync(options))50            using (var page = awaitEvaluateFunctionAsync
Using AI Code Generation
1var page = await browser.NewPageAsync();2var result = await page.EvaluateFunctionAsync("() => document.querySelector('title').innerText");3Console.WriteLine(result);4await browser.CloseAsync();5var page = await browser.NewPageAsync();6var result = await page.EvaluateExpressionAsync("document.querySelector('title').innerText");7Console.WriteLine(result);8await browser.CloseAsync();9var page = await browser.NewPageAsync();10var result = await page.EvaluateFunctionAsync("() => document.querySelector('title').innerText");11Console.WriteLine(result);12await browser.CloseAsync();13var page = await browser.NewPageAsync();14var result = await page.EvaluateExpressionAsync("document.querySelector('title').innerText");15Console.WriteLine(result);16await browser.CloseAsync();17var page = await browser.NewPageAsync();18var result = await page.EvaluateFunctionAsync("() => document.querySelector('title').innerText");19Console.WriteLine(result);20await browser.CloseAsync();21var page = await browser.NewPageAsync();22var result = await page.EvaluateExpressionAsync("document.querySelector('title').innerText");23Console.WriteLine(result);24await browser.CloseAsync();25var page = await browser.NewPageAsync();26var result = await page.EvaluateFunctionAsync("() => document.querySelector('title').innerText");27Console.WriteLine(result);28await browser.CloseAsync();29var page = await browser.NewPageAsync();30var result = await page.EvaluateExpressionAsync("document.querySelector('title').innerText");31Console.WriteLine(result);32await browser.CloseAsync();33var page = await browser.NewPageAsync();34var result = await page.EvaluateFunctionAsync("() => document.querySelector('title').innerText");35Console.WriteLine(result);36await browser.CloseAsync();EvaluateFunctionAsync
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            using (var page = await browser.NewPageAsync())11            {12                var title = await page.EvaluateFunctionAsync<string>("() => document.title");13                Console.WriteLine(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 = false }))27            using (var page = await browser.NewPageAsync())28            {29                var title = await page.EvaluateFunctionAsync<string>("() => document.title");30                Console.WriteLine(title);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            using (var page = await browser.NewPageAsync())45            {46                var title = await page.EvaluateFunctionAsync<string>("() => document.title");47                Console.WriteLine(title);48            }49        }50    }51}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!!
