Best Puppeteer-sharp code snippet using PuppeteerSharp.ExecutionContext.EvaluateExpressionAsync
PageEvaluateTests.cs
Source:PageEvaluateTests.cs
...135 [PuppeteerFact]136 public async Task ShouldSupportThrownStringsAsErrorMessages()137 {138 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(139 () => Page.EvaluateExpressionAsync("throw 'qwerty'"));140 Assert.Contains("qwerty", exception.Message);141 }142 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should support thrown numbers as error messages")]143 [PuppeteerFact]144 public async Task ShouldSupportThrownNumbersAsErrorMessages()145 {146 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(147 () => Page.EvaluateExpressionAsync("throw 100500"));148 Assert.Contains("100500", exception.Message);149 }150 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return complex objects")]151 [PuppeteerFact]152 public async Task SouldReturnComplexObjects()153 {154 dynamic obj = new155 {156 foo = "bar!"157 };158 var result = await Page.EvaluateFunctionAsync("a => a", obj);159 Assert.Equal("bar!", result.foo.ToString());160 }161 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return BigInt")]162 [PuppeteerFact]163 public async Task ShouldReturnBigInt()164 {165 var result = await Page.EvaluateFunctionAsync<object>("() => BigInt(42)");166 Assert.Equal(new BigInteger(42), result);167 }168 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return NaN")]169 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return -0")]170 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return Infinity")]171 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return -Infinity")]172 [Theory]173 [InlineData("() => NaN", double.NaN)] //ShouldReturnNaN174 [InlineData("() => -0", -0)] //ShouldReturnNegative0175 [InlineData("() => Infinity", double.PositiveInfinity)] //ShouldReturnInfinity176 [InlineData("() => -Infinity", double.NegativeInfinity)] //ShouldReturnNegativeInfinty177 public async Task BasicEvaluationTest(string script, object expected)178 {179 var result = await Page.EvaluateFunctionAsync<object>(script);180 Assert.Equal(expected, result);181 }182 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should accept \"undefined\" as one of multiple parameters")]183 [PuppeteerFact]184 public async Task ShouldAcceptNullAsOneOfMultipleParameters()185 {186 var result = await Page.EvaluateFunctionAsync<bool>(187 "(a, b) => Object.is(a, null) && Object.is(b, 'foo')",188 null,189 "foo");190 Assert.True(result);191 }192 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should return undefined for non-serializable objects")]193 [SkipBrowserFact(skipFirefox: true)]194 public async Task ShouldReturnNullForNonSerializableObjects()195 => Assert.Null(await Page.EvaluateFunctionAsync("() => window"));196 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should fail for circular object")]197 [SkipBrowserFact(skipFirefox: true)]198 public async Task ShouldFailForCircularObject()199 {200 var result = await Page.EvaluateFunctionAsync(@"() => {201 const a = {};202 const b = {a};203 a.b = b;204 return a;205 }");206 Assert.Null(result);207 }208 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should be able to throw a tricky error")]209 [SkipBrowserFact(skipFirefox: true)]210 public async Task ShouldBeAbleToThrowATrickyError()211 {212 var windowHandle = await Page.EvaluateFunctionHandleAsync("() => window");213 PuppeteerException exception = await Assert.ThrowsAsync<MessageException>(() => windowHandle.JsonValueAsync());214 var errorText = exception.Message;215 exception = await Assert.ThrowsAsync<EvaluationFailedException>(() => Page.EvaluateFunctionAsync(@"errorText =>216 {217 throw new Error(errorText);218 }", errorText));219 Assert.Contains(errorText, exception.Message);220 }221 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should accept a string")]222 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should accept a string with semi colons")]223 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should accept a string with comments")]224 [Theory]225 [InlineData("1 + 2;", 3)]226 [InlineData("1 + 5;", 6)]227 [InlineData("2 + 5\n// do some math!'", 7)]228 public async Task BasicIntExressionEvaluationTest(string script, object expected)229 {230 var result = await Page.EvaluateExpressionAsync<int>(script);231 Assert.Equal(expected, result);232 }233 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should accept element handle as an argument")]234 [PuppeteerFact]235 public async Task ShouldAcceptElementHandleAsAnArgument()236 {237 await Page.SetContentAsync("<section>42</section>");238 var element = await Page.QuerySelectorAsync("section");239 var text = await Page.EvaluateFunctionAsync<string>("e => e.textContent", element);240 Assert.Equal("42", text);241 }242 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should throw if underlying element was disposed")]243 [PuppeteerFact]244 public async Task ShouldThrowIfUnderlyingElementWasDisposed()245 {246 await Page.SetContentAsync("<section>39</section>");247 var element = await Page.QuerySelectorAsync("section");248 Assert.NotNull(element);249 await element.DisposeAsync();250 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(()251 => Page.EvaluateFunctionAsync<string>("e => e.textContent", element));252 Assert.Contains("JSHandle is disposed", exception.Message);253 }254 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should throw if elementHandles are from other frames")]255 [SkipBrowserFact(skipFirefox: true)]256 public async Task ShouldThrowIfElementHandlesAreFromOtherFrames()257 {258 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);259 var bodyHandle = await Page.FirstChildFrame().QuerySelectorAsync("body");260 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(()261 => Page.EvaluateFunctionAsync<string>("body => body.innerHTML", bodyHandle));262 Assert.Contains("JSHandles can be evaluated only in the context they were created", exception.Message);263 }264 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should simulate a user gesture")]265 [SkipBrowserFact(skipFirefox: true)]266 public async Task ShouldSimulateAUserGesture()267 => Assert.True(await Page.EvaluateFunctionAsync<bool>(@"() => {268 document.body.appendChild(document.createTextNode('test'));269 document.execCommand('selectAll');270 return document.execCommand('copy');271 }"));272 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should throw a nice error after a navigation")]273 [SkipBrowserFact(skipFirefox: true)]274 public async Task ShouldThrowANiceErrorAfterANavigation()275 {276 var executionContext = await Page.MainFrame.GetExecutionContextAsync();277 await Task.WhenAll(278 Page.WaitForNavigationAsync(),279 executionContext.EvaluateFunctionAsync("() => window.location.reload()")280 );281 var ex = await Assert.ThrowsAsync<EvaluationFailedException>(() =>282 {283 return executionContext.EvaluateFunctionAsync("() => null");284 });285 Assert.Contains("navigation", ex.Message);286 }287 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should not throw an error when evaluation does a navigation")]288 [SkipBrowserFact(skipFirefox: true)]289 public async Task ShouldNotThrowAnErrorWhenEvaluationDoesANavigation()290 {291 await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html");292 var result = await Page.EvaluateFunctionAsync<int[]>(@"() =>293 {294 window.location = '/empty.html';295 return [42];296 }");297 Assert.Equal(new[] { 42 }, result);298 }299 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should transfer 100Mb of data from page to node.js")]300 [PuppeteerFact]301 public async Task ShouldTransfer100MbOfDataFromPage()302 {303 var a = await Page.EvaluateFunctionAsync<string>("() => Array(100 * 1024 * 1024 + 1).join('a')");304 Assert.Equal(100 * 1024 * 1024, a.Length);305 }306 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should throw error with detailed information on exception inside promise ")]307 [PuppeteerFact]308 public async Task ShouldThrowErrorWithDetailedInformationOnExceptionInsidePromise()309 {310 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(() =>311 Page.EvaluateFunctionAsync(312 @"() => new Promise(() => {313 throw new Error('Error in promise');314 })"));315 Assert.Contains("Error in promise", exception.Message);316 }317 [PuppeteerFact]318 public async Task ShouldWorkWithDifferentSerializerSettings()319 {320 var result = await Page.EvaluateFunctionAsync<ComplexObjectTestClass>("() => { return { foo: 'bar' }}");321 Assert.Equal("bar", result.Foo);322 result = (await Page.EvaluateFunctionAsync<JToken>("() => { return { Foo: 'bar' }}"))323 .ToObject<ComplexObjectTestClass>(new JsonSerializerSettings());324 Assert.Equal("bar", result.Foo);325 result = await Page.EvaluateExpressionAsync<ComplexObjectTestClass>("var obj = { foo: 'bar' }; obj;");326 Assert.Equal("bar", result.Foo);327 result = (await Page.EvaluateExpressionAsync<JToken>("var obj = { Foo: 'bar' }; obj;"))328 .ToObject<ComplexObjectTestClass>(new JsonSerializerSettings());329 Assert.Equal("bar", result.Foo);330 }331 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should properly serialize null fields")]332 [PuppeteerFact]333 public async Task ShouldProperlySerializeNullFields()334 {335 var result = await Page.EvaluateFunctionAsync<Dictionary<string, object>>("() => ({a: null})");336 Assert.True(result.ContainsKey("a"));337 Assert.Null(result["a"]);338 }339 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should accept element handle as an argument")]340 [PuppeteerFact]341 public async Task ShouldAcceptObjectHandleAsAnArgument()342 {343 await Page.SetContentAsync("<section>42</section>");344 var element = await Page.QuerySelectorAsync("section");345 var text = await Page.EvaluateFunctionAsync<string>("(e) => e.textContent", element);346 Assert.Equal("42", text);347 }348 [PuppeteerFact]349 public async Task ShouldWorkWithoutGenerics()350 {351 Assert.NotNull(await Page.EvaluateExpressionAsync("var obj = {}; obj;"));352 Assert.NotNull(await Page.EvaluateExpressionAsync("[]"));353 Assert.NotNull(await Page.EvaluateExpressionAsync("''"));354 var objectPopulated = await Page.EvaluateExpressionAsync("var obj = {a:1}; obj;");355 Assert.NotNull(objectPopulated);356 Assert.Equal(1, objectPopulated["a"]);357 var arrayPopulated = await Page.EvaluateExpressionAsync("[1]");358 Assert.IsType<JArray>(arrayPopulated);359 Assert.Equal(1, ((JArray)arrayPopulated)[0]);360 Assert.Equal("1", await Page.EvaluateExpressionAsync("'1'"));361 Assert.Equal(1, await Page.EvaluateExpressionAsync("1"));362 Assert.Equal(11111111, await Page.EvaluateExpressionAsync("11111111"));363 Assert.Equal(11111111111111, await Page.EvaluateExpressionAsync("11111111111111"));364 Assert.Equal(1.1, await Page.EvaluateExpressionAsync("1.1"));365 }366 public class ComplexObjectTestClass367 {368 public string Foo { get; set; }369 }370 }371}...
EvaluateTests.cs
Source:EvaluateTests.cs
...115 [Fact]116 public async Task ShouldSupportThrownStringsAsErrorMessages()117 {118 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(119 () => Page.EvaluateExpressionAsync("throw 'qwerty'"));120 Assert.Contains("qwerty", exception.Message);121 }122 [Fact]123 public async Task ShouldSupportThrownNumbersAsErrorMessages()124 {125 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(126 () => Page.EvaluateExpressionAsync("throw 100500"));127 Assert.Contains("100500", exception.Message);128 }129 [Fact]130 public async Task SouldReturnComplexObjects()131 {132 dynamic obj = new133 {134 foo = "bar!"135 };136 var result = await Page.EvaluateFunctionAsync("a => a", obj);137 Assert.Equal("bar!", result.foo.ToString());138 }139 [Fact]140 public async Task ShouldReturnBigInt()141 {142 var result = await Page.EvaluateFunctionAsync<object>("() => BigInt(42)");143 Assert.Equal(new BigInteger(42), result);144 }145 [Theory]146 [InlineData("() => NaN", double.NaN)] //ShouldReturnNaN147 [InlineData("() => -0", -0)] //ShouldReturnNegative0148 [InlineData("() => Infinity", double.PositiveInfinity)] //ShouldReturnInfinity149 [InlineData("() => -Infinity", double.NegativeInfinity)] //ShouldReturnNegativeInfinty150 public async Task BasicEvaluationTest(string script, object expected)151 {152 var result = await Page.EvaluateFunctionAsync<object>(script);153 Assert.Equal(expected, result);154 }155 [Fact]156 public async Task ShouldAcceptNullAsOneOfMultipleParameters()157 {158 var result = await Page.EvaluateFunctionAsync<bool>(159 "(a, b) => Object.is(a, null) && Object.is(b, 'foo')",160 null,161 "foo");162 Assert.True(result);163 }164 [Fact]165 public async Task ShouldReturnNullForNonSerializableObjects()166 => Assert.Null(await Page.EvaluateFunctionAsync("() => window"));167 [Fact]168 public async Task ShouldFailForCircularObject()169 {170 var result = await Page.EvaluateFunctionAsync(@"() => {171 const a = {};172 const b = {a};173 a.b = b;174 return a;175 }");176 Assert.Null(result);177 }178 [Fact]179 public async Task ShouldBeAbleToThrowATrickyError()180 {181 var windowHandle = await Page.EvaluateFunctionHandleAsync("() => window");182 PuppeteerException exception = await Assert.ThrowsAsync<MessageException>(() => windowHandle.JsonValueAsync());183 var errorText = exception.Message;184 exception = await Assert.ThrowsAsync<EvaluationFailedException>(() => Page.EvaluateFunctionAsync(@"errorText =>185 {186 throw new Error(errorText);187 }", errorText));188 Assert.Contains(errorText, exception.Message);189 }190 [Theory]191 [InlineData("1 + 5;", 6)] //ShouldAcceptSemiColons192 [InlineData("2 + 5\n// do some math!'", 7)] //ShouldAceptStringComments193 public async Task BasicIntExressionEvaluationTest(string script, object expected)194 {195 var result = await Page.EvaluateExpressionAsync<int>(script);196 Assert.Equal(expected, result);197 }198 [Fact]199 public async Task ShouldAcceptElementHandleAsAnArgument()200 {201 await Page.SetContentAsync("<section>42</section>");202 var element = await Page.QuerySelectorAsync("section");203 var text = await Page.EvaluateFunctionAsync<string>("e => e.textContent", element);204 Assert.Equal("42", text);205 }206 [Fact]207 public async Task ShouldThrowIfUnderlyingElementWasDisposed()208 {209 await Page.SetContentAsync("<section>39</section>");210 var element = await Page.QuerySelectorAsync("section");211 Assert.NotNull(element);212 await element.DisposeAsync();213 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(()214 => Page.EvaluateFunctionAsync<string>("e => e.textContent", element));215 Assert.Contains("JSHandle is disposed", exception.Message);216 }217 [Fact]218 public async Task ShouldThrowIfElementHandlesAreFromOtherFrames()219 {220 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);221 var bodyHandle = await Page.FirstChildFrame().QuerySelectorAsync("body");222 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(()223 => Page.EvaluateFunctionAsync<string>("body => body.innerHTML", bodyHandle));224 Assert.Contains("JSHandles can be evaluated only in the context they were created", exception.Message);225 }226 [Fact]227 public async Task ShouldSimulateAUserGesture()228 => Assert.True(await Page.EvaluateFunctionAsync<bool>(@"() => {229 document.body.appendChild(document.createTextNode('test'));230 document.execCommand('selectAll');231 return document.execCommand('copy'); 232 }"));233 [Fact]234 public async Task ShouldThrowANiceErrorAfterANavigation()235 {236 var executionContext = await Page.MainFrame.GetExecutionContextAsync();237 await Task.WhenAll(238 Page.WaitForNavigationAsync(),239 executionContext.EvaluateFunctionAsync("() => window.location.reload()")240 );241 var ex = await Assert.ThrowsAsync<EvaluationFailedException>(() =>242 {243 return executionContext.EvaluateFunctionAsync("() => null");244 });245 Assert.Contains("navigation", ex.Message);246 }247 [Fact]248 public async Task ShouldNotThrowAnErrorWhenEvaluationDoesANavigation()249 {250 await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html");251 var result = await Page.EvaluateFunctionAsync<int[]>(@"() =>252 {253 window.location = '/empty.html';254 return [42];255 }");256 Assert.Equal(new[] { 42 }, result);257 }258 /// <summary>259 /// Original Name "should transfer 100Mb of data from page to node.js"260 /// </summary>261 [Fact]262 public async Task ShouldTransfer100MbOfDataFromPage()263 {264 var a = await Page.EvaluateFunctionAsync<string>("() => Array(100 * 1024 * 1024 + 1).join('a')");265 Assert.Equal(100 * 1024 * 1024, a.Length);266 }267 [Fact]268 public async Task ShouldThrowErrorWithDetailedInformationOnExceptionInsidePromise()269 {270 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(() =>271 Page.EvaluateFunctionAsync(272 @"() => new Promise(() => {273 throw new Error('Error in promise');274 })"));275 Assert.Contains("Error in promise", exception.Message);276 }277 [Fact]278 public async Task ShouldWorkWithDifferentSerializerSettings()279 {280 var result = await Page.EvaluateFunctionAsync<ComplexObjectTestClass>("() => { return { foo: 'bar' }}");281 Assert.Equal("bar", result.Foo);282 result = (await Page.EvaluateFunctionAsync<JToken>("() => { return { Foo: 'bar' }}"))283 .ToObject<ComplexObjectTestClass>(new JsonSerializerSettings());284 Assert.Equal("bar", result.Foo);285 result = await Page.EvaluateExpressionAsync<ComplexObjectTestClass>("var obj = { foo: 'bar' }; obj;");286 Assert.Equal("bar", result.Foo);287 result = (await Page.EvaluateExpressionAsync<JToken>("var obj = { Foo: 'bar' }; obj;"))288 .ToObject<ComplexObjectTestClass>(new JsonSerializerSettings());289 Assert.Equal("bar", result.Foo);290 }291 [Fact]292 public async Task ShouldProperlyIgnoreUndefinedFields()293 {294 var result = await Page.EvaluateFunctionAsync<Dictionary<string, object>>("() => ({a: undefined})");295 Assert.Empty(result);296 }297 [Fact]298 public async Task ShouldProperlySerializeNullFields()299 {300 var result = await Page.EvaluateFunctionAsync<Dictionary<string, object>>("() => ({a: null})");301 Assert.True(result.ContainsKey("a"));302 Assert.Null(result["a"]);303 }304 [Fact]305 public async Task ShouldAcceptObjectHandleAsAnArgument()306 {307 var navigatorHandle = await Page.EvaluateExpressionHandleAsync("navigator");308 var text = await Page.EvaluateFunctionAsync<string>("e => e.userAgent", navigatorHandle);309 Assert.Contains("Mozilla", text);310 }311 [Fact]312 public async Task ShouldAcceptObjectHandleToPrimitiveTypes()313 {314 var aHandle = await Page.EvaluateExpressionHandleAsync("5");315 var isFive = await Page.EvaluateFunctionAsync<bool>("e => Object.is(e, 5)", aHandle);316 Assert.True(isFive);317 }318 [Fact]319 public async Task ShouldWarnOnNestedObjectHandles()320 {321 var handle = await Page.EvaluateFunctionHandleAsync("() => document.body");322 var elementHandle = handle as ElementHandle;323 var exception = await Assert.ThrowsAsync<EvaluationFailedException>(()324 => Page.EvaluateFunctionHandleAsync(325 "opts => opts.elem.querySelector('p')",326 new { elem = handle }));327 Assert.Contains("Are you passing a nested JSHandle?", exception.Message);328 //Check with ElementHandle329 exception = await Assert.ThrowsAsync<EvaluationFailedException>(()330 => Page.EvaluateFunctionHandleAsync(331 "opts => opts.elem.querySelector('p')",332 new { elem = elementHandle }));333 Assert.Contains("Are you passing a nested JSHandle?", exception.Message);334 }335 [Fact]336 public async Task ShouldWorkWithoutGenerics()337 {338 Assert.NotNull(await Page.EvaluateExpressionAsync("var obj = {}; obj;"));339 Assert.NotNull(await Page.EvaluateExpressionAsync("[]"));340 Assert.NotNull(await Page.EvaluateExpressionAsync("''"));341 var objectPopulated = await Page.EvaluateExpressionAsync("var obj = {a:1}; obj;");342 Assert.NotNull(objectPopulated);343 Assert.Equal(1, objectPopulated["a"]);344 var arrayPopulated = await Page.EvaluateExpressionAsync("[1]");345 Assert.IsType<JArray>(arrayPopulated);346 Assert.Equal(1, ((JArray)arrayPopulated)[0]);347 Assert.Equal("1", await Page.EvaluateExpressionAsync("'1'"));348 Assert.Equal(1, await Page.EvaluateExpressionAsync("1"));349 Assert.Equal(11111111, await Page.EvaluateExpressionAsync("11111111"));350 Assert.Equal(11111111111111, await Page.EvaluateExpressionAsync("11111111111111"));351 Assert.Equal(1.1, await Page.EvaluateExpressionAsync("1.1"));352 }353 public class ComplexObjectTestClass354 {355 public string Foo { get; set; }356 }357 }358}...
DOMWorld.cs
Source:DOMWorld.cs
...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,237 options.PollingInterval,238 options.Timeout ?? _timeoutSettings.Timeout,239 args).Task;240 internal Task<JSHandle> WaitForExpressionAsync(string script, WaitForFunctionOptions options)241 => new WaitTask(242 this,243 script,244 true,245 "function",246 options.Polling,247 options.PollingInterval,248 options.Timeout ?? _timeoutSettings.Timeout).Task;249 internal Task<string> GetTitleAsync() => EvaluateExpressionAsync<string>("document.title");250 private async Task<ElementHandle> GetDocument()251 {252 if (_documentCompletionSource == null)253 {254 _documentCompletionSource = new TaskCompletionSource<ElementHandle>(TaskCreationOptions.RunContinuationsAsynchronously);255 var context = await GetExecutionContextAsync().ConfigureAwait(false);256 var document = await context.EvaluateExpressionHandleAsync("document").ConfigureAwait(false);257 _documentCompletionSource.TrySetResult(document as ElementHandle);258 }259 return await _documentCompletionSource.Task.ConfigureAwait(false);260 }261 private async Task<ElementHandle> WaitForSelectorOrXPathAsync(string selectorOrXPath, bool isXPath, WaitForSelectorOptions options = null)262 {263 options = options ?? new WaitForSelectorOptions();...
FrameWaitForSelectorTests.cs
Source:FrameWaitForSelectorTests.cs
...26 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should work with removed MutationObserver")]27 [SkipBrowserFact(skipFirefox: true)]28 public async Task ShouldWorkWithRemovedMutationObserver()29 {30 await Page.EvaluateExpressionAsync("delete window.MutationObserver");31 var waitForSelector = Page.WaitForSelectorAsync(".zombo");32 await Task.WhenAll(33 waitForSelector,34 Page.SetContentAsync("<div class='zombo'>anything</div>"));35 Assert.Equal("anything", await Page.EvaluateFunctionAsync<string>("x => x.textContent", await waitForSelector));36 }37 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should resolve promise when node is added")]38 [PuppeteerFact]39 public async Task ShouldResolveTaskWhenNodeIsAdded()40 {41 await Page.GoToAsync(TestConstants.EmptyPage);42 var frame = Page.MainFrame;43 var watchdog = frame.WaitForSelectorAsync("div");44 await frame.EvaluateFunctionAsync(AddElement, "br");45 await frame.EvaluateFunctionAsync(AddElement, "div");46 var eHandle = await watchdog;47 var property = await eHandle.GetPropertyAsync("tagName");48 var tagName = await property.JsonValueAsync<string>();49 Assert.Equal("DIV", tagName);50 }51 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should work when node is added through innerHTML")]52 [PuppeteerFact]53 public async Task ShouldWorkWhenNodeIsAddedThroughInnerHTML()54 {55 await Page.GoToAsync(TestConstants.EmptyPage);56 var watchdog = Page.WaitForSelectorAsync("h3 div");57 await Page.EvaluateFunctionAsync(AddElement, "span");58 await Page.EvaluateExpressionAsync("document.querySelector('span').innerHTML = '<h3><div></div></h3>'");59 await watchdog;60 }61 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "Page.waitForSelector is shortcut for main frame")]62 [PuppeteerFact]63 public async Task PageWaitForSelectorAsyncIsShortcutForMainFrame()64 {65 await Page.GoToAsync(TestConstants.EmptyPage);66 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);67 var otherFrame = Page.FirstChildFrame();68 var watchdog = Page.WaitForSelectorAsync("div");69 await otherFrame.EvaluateFunctionAsync(AddElement, "div");70 await Page.EvaluateFunctionAsync(AddElement, "div");71 var eHandle = await watchdog;72 Assert.Equal(Page.MainFrame, eHandle.ExecutionContext.Frame);73 }74 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should run in specified frame")]75 [PuppeteerFact]76 public async Task ShouldRunInSpecifiedFrame()77 {78 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);79 await FrameUtils.AttachFrameAsync(Page, "frame2", TestConstants.EmptyPage);80 var frame1 = Page.FirstChildFrame();81 var frame2 = Page.Frames.ElementAt(2);82 var waitForSelectorPromise = frame2.WaitForSelectorAsync("div");83 await frame1.EvaluateFunctionAsync(AddElement, "div");84 await frame2.EvaluateFunctionAsync(AddElement, "div");85 var eHandle = await waitForSelectorPromise;86 Assert.Equal(frame2, eHandle.ExecutionContext.Frame);87 }88 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should throw when frame is detached")]89 [SkipBrowserFact(skipFirefox: true)]90 public async Task ShouldThrowWhenFrameIsDetached()91 {92 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);93 var frame = Page.FirstChildFrame();94 var waitTask = frame.WaitForSelectorAsync(".box").ContinueWith(task => task?.Exception?.InnerException);95 await FrameUtils.DetachFrameAsync(Page, "frame1");96 var waitException = await waitTask;97 Assert.NotNull(waitException);98 Assert.Contains("waitForFunction failed: frame got detached.", waitException.Message);99 }100 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should survive cross-process navigation")]101 [PuppeteerFact]102 public async Task ShouldSurviveCrossProcessNavigation()103 {104 var boxFound = false;105 var waitForSelector = Page.WaitForSelectorAsync(".box").ContinueWith(_ => boxFound = true);106 await Page.GoToAsync(TestConstants.EmptyPage);107 Assert.False(boxFound);108 await Page.ReloadAsync();109 Assert.False(boxFound);110 await Page.GoToAsync(TestConstants.CrossProcessHttpPrefix + "/grid.html");111 await waitForSelector;112 Assert.True(boxFound);113 }114 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should wait for visible")]115 [PuppeteerFact]116 public async Task ShouldWaitForVisible()117 {118 var divFound = false;119 var waitForSelector = Page.WaitForSelectorAsync("div", new WaitForSelectorOptions { Visible = true })120 .ContinueWith(_ => divFound = true);121 await Page.SetContentAsync("<div style='display: none; visibility: hidden;'>1</div>");122 Assert.False(divFound);123 await Page.EvaluateExpressionAsync("document.querySelector('div').style.removeProperty('display')");124 Assert.False(divFound);125 await Page.EvaluateExpressionAsync("document.querySelector('div').style.removeProperty('visibility')");126 Assert.True(await waitForSelector);127 Assert.True(divFound);128 }129 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should wait for visible recursively")]130 [PuppeteerFact]131 public async Task ShouldWaitForVisibleRecursively()132 {133 var divVisible = false;134 var waitForSelector = Page.WaitForSelectorAsync("div#inner", new WaitForSelectorOptions { Visible = true })135 .ContinueWith(_ => divVisible = true);136 await Page.SetContentAsync("<div style='display: none; visibility: hidden;'><div id='inner'>hi</div></div>");137 Assert.False(divVisible);138 await Page.EvaluateExpressionAsync("document.querySelector('div').style.removeProperty('display')");139 Assert.False(divVisible);140 await Page.EvaluateExpressionAsync("document.querySelector('div').style.removeProperty('visibility')");141 Assert.True(await waitForSelector);142 Assert.True(divVisible);143 }144 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "hidden should wait for visibility: hidden")]145 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "hidden should wait for display: none")]146 [Theory]147 [InlineData("visibility", "hidden")]148 [InlineData("display", "none")]149 public async Task HiddenShouldWaitForVisibility(string propertyName, string propertyValue)150 {151 var divHidden = false;152 await Page.SetContentAsync("<div style='display: block;'></div>");153 var waitForSelector = Page.WaitForSelectorAsync("div", new WaitForSelectorOptions { Hidden = true })154 .ContinueWith(_ => divHidden = true);155 await Page.WaitForSelectorAsync("div"); // do a round trip156 Assert.False(divHidden);157 await Page.EvaluateExpressionAsync($"document.querySelector('div').style.setProperty('{propertyName}', '{propertyValue}')");158 Assert.True(await waitForSelector);159 Assert.True(divHidden);160 }161 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "hidden should wait for removal")]162 [PuppeteerFact]163 public async Task HiddenShouldWaitForRemoval()164 {165 await Page.SetContentAsync("<div></div>");166 var divRemoved = false;167 var waitForSelector = Page.WaitForSelectorAsync("div", new WaitForSelectorOptions { Hidden = true })168 .ContinueWith(_ => divRemoved = true);169 await Page.WaitForSelectorAsync("div"); // do a round trip170 Assert.False(divRemoved);171 await Page.EvaluateExpressionAsync("document.querySelector('div').remove()");172 Assert.True(await waitForSelector);173 Assert.True(divRemoved);174 }175 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should return null if waiting to hide non-existing element")]176 [PuppeteerFact]177 public async Task ShouldReturnNullIfWaitingToHideNonExistingElement()178 {179 var handle = await Page.WaitForSelectorAsync("non-existing", new WaitForSelectorOptions { Hidden = true });180 Assert.Null(handle);181 }182 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should respect timeout")]183 [PuppeteerFact]184 public async Task ShouldRespectTimeout()185 {186 var exception = await Assert.ThrowsAsync<WaitTaskTimeoutException>(async ()187 => await Page.WaitForSelectorAsync("div", new WaitForSelectorOptions { Timeout = 10 }));188 Assert.Contains("waiting for selector 'div' failed: timeout", exception.Message);189 }190 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should have an error message specifically for awaiting an element to be hidden")]191 [PuppeteerFact]192 public async Task ShouldHaveAnErrorMessageSpecificallyForAwaitingAnElementToBeHidden()193 {194 await Page.SetContentAsync("<div></div>");195 var exception = await Assert.ThrowsAsync<WaitTaskTimeoutException>(async ()196 => await Page.WaitForSelectorAsync("div", new WaitForSelectorOptions { Hidden = true, Timeout = 10 }));197 Assert.Contains("waiting for selector 'div' to be hidden failed: timeout", exception.Message);198 }199 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should respond to node attribute mutation")]200 [PuppeteerFact]201 public async Task ShouldRespondToNodeAttributeMutation()202 {203 var divFound = false;204 var waitForSelector = Page.WaitForSelectorAsync(".zombo").ContinueWith(_ => divFound = true);205 await Page.SetContentAsync("<div class='notZombo'></div>");206 Assert.False(divFound);207 await Page.EvaluateExpressionAsync("document.querySelector('div').className = 'zombo'");208 Assert.True(await waitForSelector);209 }210 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should return the element handle")]211 [PuppeteerFact]212 public async Task ShouldReturnTheElementHandle()213 {214 var waitForSelector = Page.WaitForSelectorAsync(".zombo");215 await Page.SetContentAsync("<div class='zombo'>anything</div>");216 Assert.Equal("anything", await Page.EvaluateFunctionAsync<string>("x => x.textContent", await waitForSelector));217 }218 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should have correct stack trace for timeout")]219 [PuppeteerFact]220 public async Task ShouldHaveCorrectStackTraceForTimeout()221 {...
ExecutionContext.cs
Source:ExecutionContext.cs
...46 /// </remarks>47 /// <seealso cref="EvaluateFunctionAsync{T}(string, object[])"/>48 /// <seealso cref="EvaluateExpressionHandleAsync(string)"/>49 /// <returns>Task which resolves to script return value</returns>50 public Task<JToken> EvaluateExpressionAsync(string script) => EvaluateExpressionAsync<JToken>(script);51 /// <summary>52 /// Executes a script in browser context53 /// </summary>54 /// <typeparam name="T">The type to deserialize the result to</typeparam>55 /// <param name="script">Script to be evaluated in browser context</param>56 /// <remarks>57 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.58 /// </remarks>59 /// <seealso cref="EvaluateFunctionAsync{T}(string, object[])"/>60 /// <seealso cref="EvaluateExpressionHandleAsync(string)"/>61 /// <returns>Task which resolves to script return value</returns>62 public Task<T> EvaluateExpressionAsync<T>(string script)63 => RemoteObjectTaskToObject<T>(EvaluateExpressionInternalAsync(true, script));64 internal async Task<JSHandle> EvaluateExpressionHandleAsync(string script)65 => CreateJSHandle(await EvaluateExpressionInternalAsync(false, script).ConfigureAwait(false));66 /// <summary>67 /// Executes a function in browser context68 /// </summary>69 /// <param name="script">Script to be evaluated in browser context</param>70 /// <param name="args">Arguments to pass to script</param>71 /// <remarks>72 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.73 /// <see cref="JSHandle"/> instances can be passed as arguments74 /// </remarks>75 /// <seealso cref="EvaluateExpressionAsync{T}(string)"/>76 /// <returns>Task which resolves to script return value</returns>77 public Task<JToken> EvaluateFunctionAsync(string script, params object[] args) => EvaluateFunctionAsync<JToken>(script, args);78 /// <summary>79 /// Executes a function in browser context80 /// </summary>81 /// <typeparam name="T">The type to deserialize the result to</typeparam>82 /// <param name="script">Script to be evaluated in browser context</param>83 /// <param name="args">Arguments to pass to script</param>84 /// <remarks>85 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.86 /// <see cref="JSHandle"/> instances can be passed as arguments87 /// </remarks>88 /// <seealso cref="EvaluateExpressionAsync{T}(string)"/>89 /// <returns>Task which resolves to script return value</returns>90 public Task<T> EvaluateFunctionAsync<T>(string script, params object[] args)91 => RemoteObjectTaskToObject<T>(EvaluateFunctionInternalAsync(true, script, args));92 internal async Task<JSHandle> EvaluateFunctionHandleAsync(string script, params object[] args)93 => CreateJSHandle(await EvaluateFunctionInternalAsync(false, script, args).ConfigureAwait(false));94 /// <summary>95 /// The method iterates JavaScript heap and finds all the objects with the given prototype.96 /// </summary>97 /// <returns>A task which resolves to a handle to an array of objects with this prototype.</returns>98 /// <param name="prototypeHandle">A handle to the object prototype.</param>99 public async Task<JSHandle> QueryObjectsAsync(JSHandle prototypeHandle)100 {101 if (prototypeHandle.Disposed)102 {...
Worker.cs
Source:Worker.cs
...71 /// <param name="script">Script to be evaluated in browser context</param>72 /// <remarks>73 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.74 /// </remarks>75 /// <seealso cref="ExecutionContext.EvaluateExpressionAsync(string)"/>76 /// <returns>Task which resolves to script return value</returns>77 public async Task<T> EvaluateExpressionAsync<T>(string script)78 => await (await ExecutionContextTask.ConfigureAwait(false)).EvaluateExpressionAsync<T>(script).ConfigureAwait(false);79 /// <summary>80 /// Executes a script in browser context81 /// </summary>82 /// <param name="script">Script to be evaluated in browser context</param>83 /// <remarks>84 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.85 /// </remarks>86 /// <returns>Task which resolves to script return value</returns>87 /// <seealso cref="ExecutionContext.EvaluateExpressionHandleAsync(string)"/>88 public async Task<JSHandle> EvaluateExpressionHandleAsync(string script)89 => await (await ExecutionContextTask.ConfigureAwait(false)).EvaluateExpressionHandleAsync(script).ConfigureAwait(false);90 internal Task<ExecutionContext> ExecutionContextTask => _executionContextCallback.Task;91 internal async void OnMessageReceived(object sender, MessageEventArgs e)92 {...
QueryObjectsTests.cs
Source:QueryObjectsTests.cs
...15 [SkipBrowserFact(skipFirefox: true)]16 public async Task ShouldWork()17 {18 // Instantiate an object19 await Page.EvaluateExpressionAsync("window.set = new Set(['hello', 'world'])");20 var prototypeHandle = await Page.EvaluateExpressionHandleAsync("Set.prototype");21 var objectsHandle = await Page.QueryObjectsAsync(prototypeHandle);22 var count = await Page.EvaluateFunctionAsync<int>("objects => objects.length", objectsHandle);23 Assert.Equal(1, count);24 var values = await Page.EvaluateFunctionAsync<string[]>("objects => Array.from(objects[0].values())", objectsHandle);25 Assert.Equal(new[] { "hello", "world" }, values);26 }27 [PuppeteerTest("page.spec.ts", "ExecutionContext.queryObjects", "should work for non-blank page")]28 [SkipBrowserFact(skipFirefox: true)]29 public async Task ShouldWorkForNonBlankPage()30 {31 // Instantiate an object32 await Page.GoToAsync(TestConstants.EmptyPage);33 await Page.EvaluateFunctionAsync("() => window.set = new Set(['hello', 'world'])");...
ExecutionContextTests.cs
Source:ExecutionContextTests.cs
...25 Assert.NotEqual(context1, context2);26 Assert.Equal(Page.MainFrame, context1.Frame);27 Assert.Equal(Page.FirstChildFrame(), context2.Frame);28 await Task.WhenAll(29 context1.EvaluateExpressionAsync("window.a = 1"),30 context2.EvaluateExpressionAsync("window.a = 2")31 );32 var a1 = context1.EvaluateExpressionAsync<int>("window.a");33 var a2 = context2.EvaluateExpressionAsync<int>("window.a");34 await Task.WhenAll(a1, a2);35 Assert.Equal(1, a1.Result);36 Assert.Equal(2, a2.Result);37 }38 }39}
EvaluateExpressionAsync
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 LaunchOptions { Headless = false });10 var page = await browser.NewPageAsync();11 await page.WaitForSelectorAsync("input[name='q']");12 await page.EvaluateExpressionAsync("document.querySelector('input[name=\"q\"]').value='puppeteer'");13 await page.ClickAsync("input[name='btnK']");14 await page.WaitForNavigationAsync();15 Console.WriteLine("Done");16 Console.ReadLine();17 await browser.CloseAsync();18 }19 }20}21using System;22using System.Threading.Tasks;23using PuppeteerSharp;24{25 {26 static async Task Main(string[] args)27 {28 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);29 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });30 var page = await browser.NewPageAsync();
EvaluateExpressionAsync
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 result = await page.EvaluateExpressionAsync<string>("document.title");14 Console.WriteLine(result);15 await browser.CloseAsync();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 result = await page.EvaluateExpressionAsync<int>("1+1");32 Console.WriteLine(result);33 await browser.CloseAsync();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 result = await page.EvaluateExpressionAsync<int>("document.querySelectorAll('a').length");50 Console.WriteLine(result);51 await browser.CloseAsync();52 }53 }54}
EvaluateExpressionAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 });11 var page = await browser.NewPageAsync();12 var element = await page.QuerySelectorAsync("input[name='q']");13 await element.TypeAsync("Puppeteer");14 var result = await page.EvaluateExpressionAsync("document.querySelector('input[name=\"q\"]').value");15 Console.WriteLine(resul
EvaluateExpressionAsync
Using AI Code Generation
1var page = await browser.NewPageAsync();2var expression = "document.querySelector('div').innerText";3var result = await page.MainFrame.EvaluateExpressionAsync<string>(expression);4Console.WriteLine(result);5var page = await browser.NewPageAsync();6var expression = "document.querySelector('div').innerText";7var result = await page.MainFrame.EvaluateExpressionAsync<string>(expression);8Console.WriteLine(result);9var page = await browser.NewPageAsync();10var expression = "document.querySelector('div').innerText";11var result = await page.MainFrame.EvaluateExpressionAsync<string>(expression);12Console.WriteLine(result);13var page = await browser.NewPageAsync();14var expression = "document.querySelector('div').innerText";15var result = await page.MainFrame.EvaluateExpressionAsync<string>(expression);16Console.WriteLine(result);17var page = await browser.NewPageAsync();18var expression = "document.querySelector('div').innerText";19var result = await page.MainFrame.EvaluateExpressionAsync<string>(expression);20Console.WriteLine(result);21var page = await browser.NewPageAsync();22var expression = "document.querySelector('div').innerText";23var result = await page.MainFrame.EvaluateExpressionAsync<string>(expression);24Console.WriteLine(result);25var page = await browser.NewPageAsync();26var expression = "document.querySelector('div').innerText";27var result = await page.MainFrame.EvaluateExpressionAsync<string>(expression);28Console.WriteLine(result);
EvaluateExpressionAsync
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 jsCode = "var x = 5;var y = 6;var z = x + y;";14 await page.EvaluateExpressionAsync(jsCode);15 var jsVariable = await page.EvaluateExpressionAsync("z");16 Console.WriteLine(jsVariable);17 var jsFunction = await page.EvaluateExpressionAsync("function add(a, b) {return a + b;}");18 Console.WriteLine(jsFunction);19 await browser.CloseAsync();20 }21 }22}23function add(a, b) {return a + b;}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 });
EvaluateExpressionAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 });11 var page = await browser.NewPageAsync();12 var result = await page.EvaluateExpressionAsync<int>("1 + 2");13 Console.WriteLine($"Result: {result}");14 await browser.CloseAsync();15 }16 }17}18using System;19using System.Threading.Tasks;20using PuppeteerSharp;21{22 {23 static async Task Main(string[] args)24 {25 var browser = await Puppeteer.LaunchAsync(new LaunchOptions26 {27 });28 var page = await browser.NewPageAsync();29 var result = await page.EvaluateExpressionAsync<int>("1 + 2").ConfigureAwait(false);30 Console.WriteLine($"
EvaluateExpressionAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"11 });12 var page = await browser.NewPageAsync();13 var result = await page.EvaluateExpressionAsync<string>("document.title");14 Console.WriteLine(result);15 Console.WriteLine("Press any key to close the browser");16 Console.ReadKey();17 await browser.CloseAsync();18 }19 }20}21using System;22using System.Threading.Tasks;23using PuppeteerSharp;24{25 {26 static async Task Main(string[] args)27 {28 var browser = await Puppeteer.LaunchAsync(new LaunchOptions29 {30 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"31 });32 var page = await browser.NewPageAsync();33 var result = await page.EvaluateExpressionAsync<string>("document.title");34 Console.WriteLine(result);35 Console.WriteLine("Press any key to close the browser");36 Console.ReadKey();37 await browser.CloseAsync();38 }39 }40}41using System;42using System.Threading.Tasks;43using PuppeteerSharp;44{45 {46 static async Task Main(string[] args)47 {
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!!