Best Puppeteer-sharp code snippet using PuppeteerSharp.JSHandle.EvaluateFunctionHandleAsync
DOMWorld.cs
Source:DOMWorld.cs  
...60        {61            var context = await GetExecutionContextAsync().ConfigureAwait(false);62            return await context.EvaluateExpressionHandleAsync(script).ConfigureAwait(false);63        }64        internal async Task<JSHandle> EvaluateFunctionHandleAsync(string script, params object[] args)65        {66            var context = await GetExecutionContextAsync().ConfigureAwait(false);67            return await context.EvaluateFunctionHandleAsync(script, args).ConfigureAwait(false);68        }69        internal async Task<T> EvaluateExpressionAsync<T>(string script)70        {71            var context = await GetExecutionContextAsync().ConfigureAwait(false);72            return await context.EvaluateExpressionAsync<T>(script).ConfigureAwait(false);73        }74        internal async Task<JToken> EvaluateExpressionAsync(string script)75        {76            var context = await GetExecutionContextAsync().ConfigureAwait(false);77            return await context.EvaluateExpressionAsync(script).ConfigureAwait(false);78        }79        internal async Task<T> EvaluateFunctionAsync<T>(string script, params object[] args)80        {81            var context = await GetExecutionContextAsync().ConfigureAwait(false);82            return await context.EvaluateFunctionAsync<T>(script, args).ConfigureAwait(false);83        }84        internal async Task<JToken> EvaluateFunctionAsync(string script, params object[] args)85        {86            var context = await GetExecutionContextAsync().ConfigureAwait(false);87            return await context.EvaluateFunctionAsync(script, args).ConfigureAwait(false);88        }89        internal Task<string> GetContentAsync() => EvaluateFunctionAsync<string>(@"() => {90                let retVal = '';91                if (document.doctype)92                    retVal = new XMLSerializer().serializeToString(document.doctype);93                if (document.documentElement)94                    retVal += document.documentElement.outerHTML;95                return retVal;96            }");97        internal async Task SetContentAsync(string html, NavigationOptions options = null)98        {99            var waitUntil = options?.WaitUntil ?? new[] { WaitUntilNavigation.Load };100            var timeout = options?.Timeout ?? _timeoutSettings.NavigationTimeout;101            // We rely upon the fact that document.open() will reset frame lifecycle with "init"102            // lifecycle event. @see https://crrev.com/608658103            await EvaluateFunctionAsync(@"html => {104                document.open();105                document.write(html);106                document.close();107            }", html).ConfigureAwait(false);108            using (var watcher = new LifecycleWatcher(_frameManager, Frame, waitUntil, timeout))109            {110                var watcherTask = await Task.WhenAny(111                    watcher.TimeoutOrTerminationTask,112                    watcher.LifecycleTask).ConfigureAwait(false);113                await watcherTask.ConfigureAwait(false);114            }115        }116        internal async Task<ElementHandle> AddScriptTagAsync(AddTagOptions options)117        {118            const string addScriptUrl = @"async function addScriptUrl(url, type) {119              const script = document.createElement('script');120              script.src = url;121              if(type)122                script.type = type;123              const promise = new Promise((res, rej) => {124                script.onload = res;125                script.onerror = rej;126              });127              document.head.appendChild(script);128              await promise;129              return script;130            }";131            const string addScriptContent = @"function addScriptContent(content, type = 'text/javascript') {132              const script = document.createElement('script');133              script.type = type;134              script.text = content;135              let error = null;136              script.onerror = e => error = e;137              document.head.appendChild(script);138              if (error)139                throw error;140              return script;141            }";142            async Task<ElementHandle> AddScriptTagPrivate(string script, string urlOrContent, string type)143            {144                var context = await GetExecutionContextAsync().ConfigureAwait(false);145                return (string.IsNullOrEmpty(type)146                        ? await context.EvaluateFunctionHandleAsync(script, urlOrContent).ConfigureAwait(false)147                        : await context.EvaluateFunctionHandleAsync(script, urlOrContent, type).ConfigureAwait(false)) as ElementHandle;148            }149            if (!string.IsNullOrEmpty(options.Url))150            {151                var url = options.Url;152                try153                {154                    return await AddScriptTagPrivate(addScriptUrl, url, options.Type).ConfigureAwait(false);155                }156                catch (PuppeteerException)157                {158                    throw new PuppeteerException($"Loading script from {url} failed");159                }160            }161            if (!string.IsNullOrEmpty(options.Path))162            {163                var contents = await AsyncFileHelper.ReadAllText(options.Path).ConfigureAwait(false);164                contents += "//# sourceURL=" + options.Path.Replace("\n", string.Empty);165                return await AddScriptTagPrivate(addScriptContent, contents, options.Type).ConfigureAwait(false);166            }167            if (!string.IsNullOrEmpty(options.Content))168            {169                return await AddScriptTagPrivate(addScriptContent, options.Content, options.Type).ConfigureAwait(false);170            }171            throw new ArgumentException("Provide options with a `Url`, `Path` or `Content` property");172        }173        internal async Task<ElementHandle> AddStyleTagAsync(AddTagOptions options)174        {175            const string addStyleUrl = @"async function addStyleUrl(url) {176              const link = document.createElement('link');177              link.rel = 'stylesheet';178              link.href = url;179              const promise = new Promise((res, rej) => {180                link.onload = res;181                link.onerror = rej;182              });183              document.head.appendChild(link);184              await promise;185              return link;186            }";187            const string addStyleContent = @"async function addStyleContent(content) {188              const style = document.createElement('style');189              style.type = 'text/css';190              style.appendChild(document.createTextNode(content));191              const promise = new Promise((res, rej) => {192                style.onload = res;193                style.onerror = rej;194              });195              document.head.appendChild(style);196              await promise;197              return style;198            }";199            if (!string.IsNullOrEmpty(options.Url))200            {201                var url = options.Url;202                try203                {204                    var context = await GetExecutionContextAsync().ConfigureAwait(false);205                    return (await context.EvaluateFunctionHandleAsync(addStyleUrl, url).ConfigureAwait(false)) as ElementHandle;206                }207                catch (PuppeteerException)208                {209                    throw new PuppeteerException($"Loading style from {url} failed");210                }211            }212            if (!string.IsNullOrEmpty(options.Path))213            {214                var contents = await AsyncFileHelper.ReadAllText(options.Path).ConfigureAwait(false);215                contents += "//# sourceURL=" + options.Path.Replace("\n", string.Empty);216                var context = await GetExecutionContextAsync().ConfigureAwait(false);217                return (await context.EvaluateFunctionHandleAsync(addStyleContent, contents).ConfigureAwait(false)) as ElementHandle;218            }219            if (!string.IsNullOrEmpty(options.Content))220            {221                var context = await GetExecutionContextAsync().ConfigureAwait(false);222                return (await context.EvaluateFunctionHandleAsync(addStyleContent, options.Content).ConfigureAwait(false)) as ElementHandle;223            }224            throw new ArgumentException("Provide options with a `Url`, `Path` or `Content` property");225        }226        internal Task<ElementHandle> WaitForSelectorAsync(string selector, WaitForSelectorOptions options = null)227            => WaitForSelectorOrXPathAsync(selector, false, options);228        internal Task<ElementHandle> WaitForXPathAsync(string xpath, WaitForSelectorOptions options = null)229            => WaitForSelectorOrXPathAsync(xpath, true, options);230        internal Task<JSHandle> WaitForFunctionAsync(string script, WaitForFunctionOptions options, params object[] args)231            => new WaitTask(232                this,233                script,234                false,235                "function",236                options.Polling,...ExecutionContext.cs
Source:ExecutionContext.cs  
...69        /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.70        /// <see cref="JSHandle"/> instances can be passed as arguments71        /// </remarks>72        /// <seealso cref="EvaluateExpressionAsync{T}(string)"/>73        /// <seealso cref="EvaluateFunctionHandleAsync(string, object[])"/>74        /// <returns>Task which resolves to script return value</returns>75        public Task<JToken> EvaluateFunctionAsync(string script, params object[] args)76            => EvaluateAsync<JToken>(EvaluateFunctionHandleAsync(script, args));77        /// <summary>78        /// Executes a function in browser context79        /// </summary>80        /// <typeparam name="T">The type to deserialize the result to</typeparam>81        /// <param name="script">Script to be evaluated in browser context</param>82        /// <param name="args">Arguments to pass to script</param>83        /// <remarks>84        /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.85        /// <see cref="JSHandle"/> instances can be passed as arguments86        /// </remarks>87        /// <seealso cref="EvaluateExpressionAsync{T}(string)"/>88        /// <seealso cref="EvaluateFunctionHandleAsync(string, object[])"/>89        /// <returns>Task which resolves to script return value</returns>90        public Task<T> EvaluateFunctionAsync<T>(string script, params object[] args)91            => EvaluateAsync<T>(EvaluateFunctionHandleAsync(script, args));92        /// <summary>93        /// The method iterates JavaScript heap and finds all the objects with the given prototype.94        /// </summary>95        /// <returns>A task which resolves to a handle to an array of objects with this prototype.</returns>96        /// <param name="prototypeHandle">A handle to the object prototype.</param>97        public async Task<JSHandle> QueryObjectsAsync(JSHandle prototypeHandle)98        {99            if (prototypeHandle.Disposed)100            {101                throw new PuppeteerException("Prototype JSHandle is disposed!");102            }103            if (!((JObject)prototypeHandle.RemoteObject).TryGetValue(MessageKeys.ObjectId, out var objectId))104            {105                throw new PuppeteerException("Prototype JSHandle must not be referencing primitive value");106            }107            var response = await _client.SendAsync("Runtime.queryObjects", new Dictionary<string, object>108            {109                {"prototypeObjectId", objectId.ToString()}110            }).ConfigureAwait(false);111            return CreateJSHandle(response[MessageKeys.Objects]);112        }113        internal async Task<JSHandle> EvaluateExpressionHandleAsync(string script)114        {115            if (string.IsNullOrEmpty(script))116            {117                return null;118            }119            try120            {121                return await EvaluateHandleAsync("Runtime.evaluate", new Dictionary<string, object>122                {123                    ["expression"] = _sourceUrlRegex.IsMatch(script) ? script : $"{script}\n{EvaluationScriptSuffix}",124                    ["contextId"] = _contextId,125                    ["returnByValue"] = false,126                    ["awaitPromise"] = true,127                    ["userGesture"] = true128                }).ConfigureAwait(false);129            }130            catch (Exception ex)131            {132                throw new EvaluationFailedException(ex.Message, ex);133            }134        }135        internal async Task<JSHandle> EvaluateFunctionHandleAsync(string script, params object[] args)136        {137            if (string.IsNullOrEmpty(script))138            {139                return null;140            }141            try142            {143                return await EvaluateHandleAsync("Runtime.callFunctionOn", new Dictionary<string, object>144                {145                    ["functionDeclaration"] = $"{script}\n{EvaluationScriptSuffix}\n",146                    [MessageKeys.ExecutionContextId] = _contextId,147                    ["arguments"] = args.Select(FormatArgument),148                    ["returnByValue"] = false,149                    ["awaitPromise"] = true,...JSHandle.cs
Source:JSHandle.cs  
...7using System.Threading.Tasks;8namespace PuppeteerSharp9{10    /// <summary>11    /// JSHandle represents an in-page JavaScript object. JSHandles can be created with the <see cref="Page.EvaluateExpressionHandleAsync(string)"/> and <see cref="Page.EvaluateFunctionHandleAsync(string, object[])"/> methods.12    /// </summary>13    [JsonConverter(typeof(JSHandleMethodConverter))]14    public class JSHandle15    {16        internal JSHandle(ExecutionContext context, CDPSession client, RemoteObject remoteObject)17        {18            ExecutionContext = context;19            Client = client;20            RemoteObject = remoteObject;21        }22        /// <summary>23        /// Gets the execution context.24        /// </summary>25        /// <value>The execution context.</value>26        public ExecutionContext ExecutionContext { get; }27        /// <summary>28        /// Gets or sets a value indicating whether this <see cref="JSHandle"/> is disposed.29        /// </summary>30        /// <value><c>true</c> if disposed; otherwise, <c>false</c>.</value>31        public bool Disposed { get; private set; }32        /// <summary>33        /// Gets or sets the remote object.34        /// </summary>35        /// <value>The remote object.</value>36        public RemoteObject RemoteObject { get; }37        /// <summary>38        /// Gets the client.39        /// </summary>40        /// <value>The client.</value>41        protected CDPSession Client { get; }42        /// <summary>43        /// Fetches a single property from the referenced object44        /// </summary>45        /// <param name="propertyName">property to get</param>46        /// <returns>Task of <see cref="JSHandle"/></returns>47        public async Task<JSHandle> GetPropertyAsync(string propertyName)48        {49            var objectHandle = await EvaluateFunctionHandleAsync(@"(object, propertyName) => {50              const result = { __proto__: null};51              result[propertyName] = object[propertyName];52              return result;53            }", propertyName).ConfigureAwait(false);54            var properties = await objectHandle.GetPropertiesAsync().ConfigureAwait(false);55            properties.TryGetValue(propertyName, out var result);56            await objectHandle.DisposeAsync().ConfigureAwait(false);57            return result;58        }59        /// <summary>60        /// Returns a <see cref="Dictionary{TKey, TValue}"/> with property names as keys and <see cref="JSHandle"/> instances for the property values.61        /// </summary>62        /// <returns>Task which resolves to a <see cref="Dictionary{TKey, TValue}"/></returns>63        /// <example>64        /// <code>65        /// var handle = await page.EvaluateExpressionHandle("({window, document})");66        /// var properties = await handle.GetPropertiesAsync();67        /// var windowHandle = properties["window"];68        /// var documentHandle = properties["document"];69        /// await handle.DisposeAsync();70        /// </code>71        /// </example>72        public async Task<Dictionary<string, JSHandle>> GetPropertiesAsync()73        {74            var response = await Client.SendAsync<RuntimeGetPropertiesResponse>("Runtime.getProperties", new RuntimeGetPropertiesRequest75            {76                ObjectId = RemoteObject.ObjectId,77                OwnProperties = true78            }).ConfigureAwait(false);79            var result = new Dictionary<string, JSHandle>();80            foreach (var property in response.Result)81            {82                if (property.Enumerable == null)83                {84                    continue;85                }86                result.Add(property.Name, ExecutionContext.CreateJSHandle(property.Value));87            }88            return result;89        }90        /// <summary>91        /// Returns a JSON representation of the object92        /// </summary>93        /// <returns>Task</returns>94        /// <remarks>95        /// The method will return an empty JSON if the referenced object is not stringifiable. It will throw an error if the object has circular references96        /// </remarks>97        public async Task<object> JsonValueAsync() => await JsonValueAsync<object>().ConfigureAwait(false);98        /// <summary>99        /// Returns a JSON representation of the object100        /// </summary>101        /// <typeparam name="T">A strongly typed object to parse to</typeparam>102        /// <returns>Task</returns>103        /// <remarks>104        /// The method will return an empty JSON if the referenced object is not stringifiable. It will throw an error if the object has circular references105        /// </remarks>106        public async Task<T> JsonValueAsync<T>()107        {108            var objectId = RemoteObject.ObjectId;109            if (objectId != null)110            {111                var response = await Client.SendAsync<RuntimeCallFunctionOnResponse>("Runtime.callFunctionOn", new RuntimeCallFunctionOnRequest112                {113                    FunctionDeclaration = "function() { return this; }",114                    ObjectId = objectId,115                    ReturnByValue = true,116                    AwaitPromise = true117                }).ConfigureAwait(false);118                return (T)RemoteObjectHelper.ValueFromRemoteObject<T>(response.Result);119            }120            return (T)RemoteObjectHelper.ValueFromRemoteObject<T>(RemoteObject);121        }122        /// <summary>123        /// Disposes the Handle. It will mark the JSHandle as disposed and release the <see cref="JSHandle.RemoteObject"/>124        /// </summary>125        /// <returns>The async.</returns>126        public async Task DisposeAsync()127        {128            if (Disposed)129            {130                return;131            }132            Disposed = true;133            await RemoteObjectHelper.ReleaseObjectAsync(Client, RemoteObject).ConfigureAwait(false);134        }135        /// <inheritdoc/>136        public override string ToString()137        {138            if (RemoteObject.ObjectId != null)139            {140                var type = RemoteObject.Subtype != RemoteObjectSubtype.Other141                    ? RemoteObject.Subtype.ToString()142                    : RemoteObject.Type.ToString();143                return "JSHandle@" + type.ToLower(System.Globalization.CultureInfo.CurrentCulture);144            }145            return "JSHandle:" + RemoteObjectHelper.ValueFromRemoteObject<object>(RemoteObject)?.ToString();146        }147        /// <summary>148        /// Executes a script in browser context149        /// </summary>150        /// <param name="pageFunction">Script to be evaluated in browser context</param>151        /// <param name="args">Function arguments</param>152        /// <remarks>153        /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.154        /// <see cref="JSHandle"/> instances can be passed as arguments155        /// </remarks>156        /// <returns>Task which resolves to script return value</returns>157        public Task<JSHandle> EvaluateFunctionHandleAsync(string pageFunction, params object[] args)158        {159            var list = new List<object>(args);160            list.Insert(0, this);161            return ExecutionContext.EvaluateFunctionHandleAsync(pageFunction, list.ToArray());162        }163        /// <summary>164        /// Executes a function in browser context165        /// </summary>166        /// <param name="script">Script to be evaluated in browser context</param>167        /// <param name="args">Arguments to pass to script</param>168        /// <remarks>169        /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.170        /// <see cref="JSHandle"/> instances can be passed as arguments171        /// </remarks>172        /// <returns>Task which resolves to script return value</returns>173        public Task<JToken> EvaluateFunctionAsync(string script, params object[] args)174        {175            var list = new List<object>(args);...WaitTask.cs
Source:WaitTask.cs  
...142            Exception exception = null;143            var context = await _frame.GetExecutionContextAsync().ConfigureAwait(false);144            try145            {146                success = await context.EvaluateFunctionHandleAsync(WaitForPredicatePageFunction,147                    new object[] { _predicateBody, _pollingInterval ?? (object)_polling, _timeout }.Concat(_args).ToArray()).ConfigureAwait(false);148            }149            catch (Exception ex)150            {151                exception = ex;152            }153            if (_terminated || runCount != _runCount)154            {155                if (success != null)156                {157                    await success.DisposeAsync().ConfigureAwait(false);158                }159                return;160            }...PageEvaluateHandle.cs
Source:PageEvaluateHandle.cs  
...13        }14        [PuppeteerTest("jshandle.spec.ts", "Page.evaluateHandle", "should work")]15        [PuppeteerFact]16        public async Task ShouldWork()17            => Assert.NotNull(await Page.EvaluateFunctionHandleAsync("() => window"));18        [PuppeteerTest("jshandle.spec.ts", "Page.evaluateHandle", "should accept object handle as an argument")]19        [PuppeteerFact]20        public async Task ShouldAcceptObjectHandleAsAnArgument()21        {22            var navigatorHandle = await Page.EvaluateFunctionHandleAsync("() => navigator");23            var text = await Page.EvaluateFunctionAsync<string>(24                "(e) => e.userAgent",25                navigatorHandle);26            Assert.Contains("Mozilla", text);27        }28        [PuppeteerTest("jshandle.spec.ts", "Page.evaluateHandle", "should accept object handle to primitive types")]29        [PuppeteerFact]30        public async Task ShouldAcceptObjectHandleToPrimitiveTypes()31        {32            var aHandle = await Page.EvaluateFunctionHandleAsync("() => 5");33            var isFive = await Page.EvaluateFunctionAsync<bool>(34                "(e) => Object.is(e, 5)",35                aHandle);36            Assert.True(isFive);37        }38        [PuppeteerTest("jshandle.spec.ts", "Page.evaluateHandle", "should warn on nested object handles")]39        [PuppeteerFact]40        public async Task ShouldWarnOnNestedObjectHandles()41        {42            var aHandle = await Page.EvaluateFunctionHandleAsync("() => document.body");43            var exception = await Assert.ThrowsAsync<EvaluationFailedException>(() =>44                Page.EvaluateFunctionHandleAsync("(opts) => opts.elem.querySelector('p')", new { aHandle }));45            Assert.Contains("Are you passing a nested JSHandle?", exception.Message);46        }47        [PuppeteerTest("jshandle.spec.ts", "Page.evaluateHandle", "should accept object handle to unserializable value")]48        [PuppeteerFact]49        public async Task ShouldAcceptObjectHandleToUnserializableValue()50        {51            var aHandle = await Page.EvaluateFunctionHandleAsync("() => Infinity");52            Assert.True(await Page.EvaluateFunctionAsync<bool>(53                "(e) => Object.is(e, Infinity)",54                aHandle));55        }56        [PuppeteerTest("jshandle.spec.ts", "Page.evaluateHandle", "should use the same JS wrappers")]57        [PuppeteerFact]58        public async Task ShouldUseTheSameJSWrappers()59        {60            var aHandle = await Page.EvaluateFunctionHandleAsync(@"() => {61                globalThis.FOO = 123;62                return window;63            }");64            Assert.Equal(123, await Page.EvaluateFunctionAsync<int>(65                "(e) => e.FOO",66                aHandle));67        }68    }69}...JsonValueTests.cs
Source:JsonValueTests.cs  
...23        [PuppeteerTest("jshandle.spec.ts", "JSHandle.jsonValue", "works with jsonValues that are not objects")]24        [SkipBrowserFact(skipFirefox: true)]25        public async Task WorksWithJsonValuesThatAreNotObjects()26        {27            var aHandle = await Page.EvaluateFunctionHandleAsync("() => ['a', 'b']");28            var json = await aHandle.JsonValueAsync<string[]>();29            Assert.Equal(new[] {"a","b" }, json);30        }31        [PuppeteerTest("jshandle.spec.ts", "JSHandle.jsonValue", "works with jsonValues that are primitives")]32        [SkipBrowserFact(skipFirefox: true)]33        public async Task WorksWithJsonValuesThatArePrimitives()34        {35            var aHandle = await Page.EvaluateFunctionHandleAsync("() => 'foo'");36            var json = await aHandle.JsonValueAsync<string>();37            Assert.Equal("foo", json);38        }39        [PuppeteerTest("jshandle.spec.ts", "JSHandle.jsonValue", "should not work with dates")]40        [SkipBrowserFact(skipFirefox: true)]41        public async Task ShouldNotWorkWithDates()42        {43            var dateHandle = await Page.EvaluateExpressionHandleAsync("new Date('2017-09-26T00:00:00.000Z')");44            var json = await dateHandle.JsonValueAsync();45            Assert.Equal(JObject.Parse("{}"), json);46        }47        [PuppeteerTest("jshandle.spec.ts", "JSHandle.jsonValue", "should throw for circular objects")]48        [PuppeteerFact]49        public async Task ShouldThrowForCircularObjects()...QueryObjectsTests.cs
Source:QueryObjectsTests.cs  
...26        {27            // Instantiate an object28            await Page.GoToAsync(TestConstants.EmptyPage);29            await Page.EvaluateFunctionAsync("() => window.set = new Set(['hello', 'world'])");30            var prototypeHandle = await Page.EvaluateFunctionHandleAsync("() => Set.prototype");31            var objectsHandle = await Page.QueryObjectsAsync(prototypeHandle);32            var count = await Page.EvaluateFunctionAsync<int>("objects => objects.length", objectsHandle);33            Assert.Equal(1, count);34        }35        [Fact]36        public async Task ShouldFailForDisposedHandles()37        {38            var prototypeHandle = await Page.EvaluateExpressionHandleAsync("HTMLBodyElement.prototype");39            await prototypeHandle.DisposeAsync();40            var exception = await Assert.ThrowsAsync<PuppeteerException>(()41                => Page.QueryObjectsAsync(prototypeHandle));42            Assert.Equal("Prototype JSHandle is disposed!", exception.Message);43        }44        [Fact]...GetPropertiesTests.cs
Source:GetPropertiesTests.cs  
...26        [PuppeteerTest("jshandle.spec.ts", "JSHandle.getProperties", "should return even non-own properties")]27        [PuppeteerFact]28        public async Task ShouldReturnEvenNonOwnProperties()29        {30            var aHandle = await Page.EvaluateFunctionHandleAsync(@"() => {31              class A {32                constructor() {33                  this.a = '1';34                }35              }36              class B extends A {37                constructor() {38                  super();39                  this.b = '2';40                }41              }42              return new B();43            }");44            var properties = await aHandle.GetPropertiesAsync();...EvaluateFunctionHandleAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5    {6        static async Task Main(string[] args)7        {8            var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });9            var page = await browser.NewPageAsync();10            var jsHandle = await page.EvaluateFunctionHandleAsync(@"() => {11                return {12                };13            }");14            var result = await jsHandle.EvaluateFunctionHandleAsync(@"(obj) => {15                return {16                };17            }", jsHandle);18            Console.WriteLine(result);19            await browser.CloseAsync();20        }21    }22}23using System;24using System.Threading.Tasks;25using PuppeteerSharp;26{27    {28        static async Task Main(string[] args)29        {30            var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });31            var page = await browser.NewPageAsync();32            var jsHandle = await page.EvaluateFunctionHandleAsync(@"() => {33                return {34                };35            }");36            var result = await jsHandle.EvaluateFunctionHandleAsync(@"(obj) => {37                return {38                };39            }", jsHandle);40            var json = await result.JsonValueAsync();41            Console.WriteLine(json);42            await browser.CloseAsync();43        }44    }45}46{47  "obj": {48    "window": {},49    "document": {}50  },51  "x": {}52}53using System;54using System.Threading.Tasks;55using PuppeteerSharp;56{57    {58        static async Task Main(string[] args)59        {60            var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });61            var page = await browser.NewPageAsync();EvaluateFunctionHandleAsync
Using AI Code Generation
1var page = await browser.NewPageAsync();2var result = await page.EvaluateFunctionHandleAsync(@"() => {3    return {4    };5}");6var windowHandle = await result.GetPropertyAsync("window");7var documentHandle = await result.GetPropertyAsync("document");8await windowHandle.DisposeAsync();9await documentHandle.DisposeAsync();10await result.DisposeAsync();11var page = await browser.NewPageAsync();12var result = await page.EvaluateFunctionHandleAsync(@"() => {13    return {14    };15}");16var windowHandle = await result.GetPropertyAsync("window");17var documentHandle = await result.GetPropertyAsync("document");18await windowHandle.DisposeAsync();19await documentHandle.DisposeAsync();20await result.DisposeAsync();21var page = await browser.NewPageAsync();22var frame = page.MainFrame;23var result = await frame.EvaluateFunctionHandleAsync(@"() => {24    return {25    };26}");27var windowHandle = await result.GetPropertyAsync("window");28var documentHandle = await result.GetPropertyAsync("document");29await windowHandle.DisposeAsync();30await documentHandle.DisposeAsync();31await result.DisposeAsync();32var page = await browser.NewPageAsync();33var elementHandle = await page.QuerySelectorAsync("body");34var result = await elementHandle.EvaluateFunctionHandleAsync(@"() => {35    return {36    };37}");38var windowHandle = await result.GetPropertyAsync("window");39var documentHandle = await result.GetPropertyAsync("document");40await windowHandle.DisposeAsync();41await documentHandle.DisposeAsync();42await result.DisposeAsync();43await elementHandle.DisposeAsync();44var page = await browser.NewPageAsync();45var result = await page.EvaluateFunctionHandleAsync(@"() => {46    return {EvaluateFunctionHandleAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5    {6        static async Task Main(string[] args)7        {8            var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });9            var page = await browser.NewPageAsync();10            var functionHandle = await page.EvaluateFunctionHandleAsync("() => document.body");11            var result = await functionHandle.EvaluateFunctionHandleAsync("body => body.innerHTML");12            Console.WriteLine(result);13            await browser.CloseAsync();14        }15    }16}17using System;18using System.Threading.Tasks;19using PuppeteerSharp;20{21    {22        static async Task Main(string[] args)23        {24            var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });25            var page = await browser.NewPageAsync();26            var functionHandle = await page.EvaluateFunctionHandleAsync("() => document.body");27            var result = await functionHandle.EvaluateFunctionHandleAsync("body => body.innerHTML", new object[] { functionHandle });28            Console.WriteLine(result);29            await browser.CloseAsync();30        }31    }32}33using System;EvaluateFunctionHandleAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5    {6        static void Main(string[] args)7        {8            MainAsync(args).GetAwaiter().GetResult();9        }10        static async Task MainAsync(string[] args)11        {12            var browser = await Puppeteer.LaunchAsync(new LaunchOptions13            {14            });15            var page = await browser.NewPageAsync();16            var handle = await page.EvaluateFunctionHandleAsync("() => Promise.resolve(8 * 7)");17            var result = await handle.JsonValueAsync();18            Console.WriteLine(result);19            await browser.CloseAsync();20        }21    }22}EvaluateFunctionHandleAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5    {6        static async Task Main(string[] args)7        {8            var browser = await Puppeteer.LaunchAsync(new LaunchOptions9            {10            });11            var page = await browser.NewPageAsync();12            var result = await page.EvaluateFunctionHandleAsync("() => document.title");13            Console.WriteLine(await result.JsonValueAsync());14        }15    }16}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!!
