How to use DisposeAsync method of PuppeteerSharp.JSHandle class

Best Puppeteer-sharp code snippet using PuppeteerSharp.JSHandle.DisposeAsync

DOMWorld.cs

Source:DOMWorld.cs Github

copy

Full Screen

...250 {251 throw new SelectorException($"No node found for selector: {selector}", selector);252 }253 await handle.ClickAsync(options).ConfigureAwait(false);254 await handle.DisposeAsync().ConfigureAwait(false);255 }256 internal async Task HoverAsync(string selector)257 {258 var handle = await QuerySelectorAsync(selector).ConfigureAwait(false);259 if (handle == null)260 {261 throw new SelectorException($"No node found for selector: {selector}", selector);262 }263 await handle.HoverAsync().ConfigureAwait(false);264 await handle.DisposeAsync().ConfigureAwait(false);265 }266 internal async Task FocusAsync(string selector)267 {268 var handle = await QuerySelectorAsync(selector).ConfigureAwait(false);269 if (handle == null)270 {271 throw new SelectorException($"No node found for selector: {selector}", selector);272 }273 await handle.FocusAsync().ConfigureAwait(false);274 await handle.DisposeAsync().ConfigureAwait(false);275 }276 internal async Task<string[]> SelectAsync(string selector, params string[] values)277 {278 if (!((await QuerySelectorAsync(selector).ConfigureAwait(false)) is ElementHandle handle))279 {280 throw new SelectorException($"No node found for selector: {selector}", selector);281 }282 var result = await handle.SelectAsync(values).ConfigureAwait(false);283 await handle.DisposeAsync();284 return result;285 }286 internal async Task TapAsync(string selector)287 {288 var handle = await QuerySelectorAsync(selector).ConfigureAwait(false);289 if (handle == null)290 {291 throw new SelectorException($"No node found for selector: {selector}", selector);292 }293 await handle.TapAsync().ConfigureAwait(false);294 await handle.DisposeAsync().ConfigureAwait(false);295 }296 internal async Task TypeAsync(string selector, string text, TypeOptions options = null)297 {298 var handle = await QuerySelectorAsync(selector).ConfigureAwait(false);299 if (handle == null)300 {301 throw new SelectorException($"No node found for selector: {selector}", selector);302 }303 await handle.TypeAsync(text, options).ConfigureAwait(false);304 await handle.DisposeAsync().ConfigureAwait(false);305 }306 internal Task<ElementHandle> WaitForSelectorAsync(string selector, WaitForSelectorOptions options = null)307 => WaitForSelectorOrXPathAsync(selector, false, options);308 internal Task<ElementHandle> WaitForXPathAsync(string xpath, WaitForSelectorOptions options = null)309 => WaitForSelectorOrXPathAsync(xpath, true, options);310 internal Task<JSHandle> WaitForFunctionAsync(string script, WaitForFunctionOptions options, params object[] args)311 => new WaitTask(312 this,313 script,314 false,315 "function",316 options.Polling,317 options.PollingInterval,318 options.Timeout ?? _timeoutSettings.Timeout,319 args).Task;320 internal Task<JSHandle> WaitForExpressionAsync(string script, WaitForFunctionOptions options)321 => new WaitTask(322 this,323 script,324 true,325 "function",326 options.Polling,327 options.PollingInterval,328 options.Timeout ?? _timeoutSettings.Timeout).Task;329 internal Task<string> GetTitleAsync() => EvaluateExpressionAsync<string>("document.title");330 private async Task<ElementHandle> GetDocument()331 {332 if (_documentCompletionSource == null)333 {334 _documentCompletionSource = new TaskCompletionSource<ElementHandle>(TaskCreationOptions.RunContinuationsAsynchronously);335 var context = await GetExecutionContextAsync().ConfigureAwait(false);336 var document = await context.EvaluateExpressionHandleAsync("document").ConfigureAwait(false);337 _documentCompletionSource.TrySetResult(document as ElementHandle);338 }339 return await _documentCompletionSource.Task.ConfigureAwait(false);340 }341 private async Task<ElementHandle> WaitForSelectorOrXPathAsync(string selectorOrXPath, bool isXPath, WaitForSelectorOptions options = null)342 {343 options = options ?? new WaitForSelectorOptions();344 var timeout = options.Timeout ?? _timeoutSettings.Timeout;345 const string predicate = @"346 function predicate(selectorOrXPath, isXPath, waitForVisible, waitForHidden) {347 const node = isXPath348 ? document.evaluate(selectorOrXPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue349 : document.querySelector(selectorOrXPath);350 if (!node)351 return waitForHidden;352 if (!waitForVisible && !waitForHidden)353 return node;354 const element = node.nodeType === Node.TEXT_NODE ? node.parentElement : node;355 const style = window.getComputedStyle(element);356 const isVisible = style && style.visibility !== 'hidden' && hasVisibleBoundingBox();357 const success = (waitForVisible === isVisible || waitForHidden === !isVisible);358 return success ? node : null;359 function hasVisibleBoundingBox() {360 const rect = element.getBoundingClientRect();361 return !!(rect.top || rect.bottom || rect.width || rect.height);362 }363 }";364 var polling = options.Visible || options.Hidden ? WaitForFunctionPollingOption.Raf : WaitForFunctionPollingOption.Mutation;365 var handle = await new WaitTask(366 this,367 predicate,368 false,369 $"{(isXPath ? "XPath" : "selector")} '{selectorOrXPath}'{(options.Hidden ? " to be hidden" : "")}",370 polling,371 null,372 timeout,373 new object[]374 {375 selectorOrXPath,376 isXPath,377 options.Visible,378 options.Hidden379 }).Task.ConfigureAwait(false);380 if (!(handle is ElementHandle elementHandle))381 {382 await handle?.DisposeAsync();383 return null;384 }385 return elementHandle;386 }387 }388}...

Full Screen

Full Screen

ExecutionContext.cs

Source:ExecutionContext.cs Github

copy

Full Screen

...176 return default;177 }178 throw new EvaluationFailedException(ex.Message, ex);179 }180 await handle.DisposeAsync().ConfigureAwait(false);181 return result is JToken token && token.Type == JTokenType.Null ? default : result;182 }183 private async Task<JSHandle> EvaluateHandleAsync(string method, dynamic args)184 {185 var response = await _client.SendAsync(method, args).ConfigureAwait(false);186 var exceptionDetails = response[MessageKeys.ExceptionDetails];187 if (exceptionDetails != null)188 {189 throw new EvaluationFailedException("Evaluation failed: " +190 GetExceptionMessage(exceptionDetails.ToObject<EvaluateExceptionDetails>()));191 }192 return CreateJSHandle(response.result);193 }194 private object FormatArgument(object arg)...

Full Screen

Full Screen

JSHandle.cs

Source:JSHandle.cs Github

copy

Full Screen

...56 return result;57 }", this, propertyName).ConfigureAwait(false);58 var properties = await objectHandle.GetPropertiesAsync().ConfigureAwait(false);59 properties.TryGetValue(propertyName, out var result);60 await objectHandle.DisposeAsync().ConfigureAwait(false);61 return result;62 }63 /// <summary>64 /// Returns a <see cref="Dictionary{TKey, TValue}"/> with property names as keys and <see cref="JSHandle"/> instances for the property values.65 /// </summary>66 /// <returns>Task which resolves to a <see cref="Dictionary{TKey, TValue}"/></returns>67 /// <example>68 /// <code>69 /// var handle = await page.EvaluateExpressionHandle("({window, document})");70 /// var properties = await handle.GetPropertiesAsync();71 /// var windowHandle = properties["window"];72 /// var documentHandle = properties["document"];73 /// await handle.DisposeAsync();74 /// </code>75 /// </example>76 public async Task<Dictionary<string, JSHandle>> GetPropertiesAsync()77 {78 var response = await Client.SendAsync("Runtime.getProperties", new79 {80 objectId = RemoteObject[MessageKeys.ObjectId].AsString(),81 ownProperties = true82 }).ConfigureAwait(false);83 var result = new Dictionary<string, JSHandle>();84 foreach (var property in response[MessageKeys.Result])85 {86 if (property[MessageKeys.Enumerable] == null)87 {88 continue;89 }90 result.Add(property[MessageKeys.Name].AsString(), ExecutionContext.CreateJSHandle(property[MessageKeys.Value]));91 }92 return result;93 }94 /// <summary>95 /// Returns a JSON representation of the object96 /// </summary>97 /// <returns>Task</returns>98 /// <remarks>99 /// The method will return an empty JSON if the referenced object is not stringifiable. It will throw an error if the object has circular references100 /// </remarks>101 public async Task<object> JsonValueAsync() => await JsonValueAsync<object>().ConfigureAwait(false);102 /// <summary>103 /// Returns a JSON representation of the object104 /// </summary>105 /// <typeparam name="T">A strongly typed object to parse to</typeparam>106 /// <returns>Task</returns>107 /// <remarks>108 /// The method will return an empty JSON if the referenced object is not stringifiable. It will throw an error if the object has circular references109 /// </remarks>110 public async Task<T> JsonValueAsync<T>()111 {112 var objectId = RemoteObject[MessageKeys.ObjectId];113 if (objectId != null)114 {115 var response = await Client.SendAsync("Runtime.callFunctionOn", new Dictionary<string, object>116 {117 ["functionDeclaration"] = "function() { return this; }",118 [MessageKeys.ObjectId] = objectId,119 ["returnByValue"] = true,120 ["awaitPromise"] = true121 }).ConfigureAwait(false);122 return (T)RemoteObjectHelper.ValueFromRemoteObject<T>(response[MessageKeys.Result]);123 }124 return (T)RemoteObjectHelper.ValueFromRemoteObject<T>(RemoteObject);125 }126 /// <summary>127 /// Disposes the Handle. It will mark the JSHandle as disposed and release the <see cref="JSHandle.RemoteObject"/>128 /// </summary>129 /// <returns>The async.</returns>130 public async Task DisposeAsync()131 {132 if (Disposed)133 {134 return;135 }136 Disposed = true;137 await RemoteObjectHelper.ReleaseObject(Client, RemoteObject, Logger).ConfigureAwait(false);138 }139 /// <inheritdoc/>140 public override string ToString()141 {142 if ((RemoteObject)[MessageKeys.ObjectId] != null)143 {144 var type = RemoteObject[MessageKeys.Subtype] ?? RemoteObject[MessageKeys.Type];...

Full Screen

Full Screen

WaitTask.cs

Source:WaitTask.cs Github

copy

Full Screen

...137 exception = ex;138 }139 if (_terminated || runCount != _runCount)140 {141 if (success != null) await success.DisposeAsync();142 return;143 }144 if (exception == null && await _frame.EvaluateFunctionAsync<bool>("s => !s", success))145 {146 if (success != null) await success.DisposeAsync();147 return;148 }149 if (exception?.Message.Contains("Execution context was destroyed") == true)150 {151 return;152 }153 if (exception?.Message.Contains("Cannot find context with specified id") == true)154 {155 return;156 }157 if (exception != null)158 {159 _taskCompletion.SetException(exception);160 }...

Full Screen

Full Screen

YandexMapsClient.cs

Source:YandexMapsClient.cs Github

copy

Full Screen

...22 static readonly Func<Location, Location, string> UrlTemplate = (x, y) =>23 $"https://yandex.by/maps/157/minsk/?mode=routes&rtext={x}~{y}&rtt=mt&z=13";24 readonly Page _page;25 YandexMapsClient(Page page) => _page = page;26 public async ValueTask DisposeAsync()27 {28 await _page.DisposeAsync();29 await _page.Browser.DisposeAsync();30 }31 public static async Task<YandexMapsClient> Launch()32 {33 var browser = await Puppeteer.LaunchAsync(new LaunchOptions34 {35 Headless = true,36 DefaultViewport = ViewPort,37 Args = new[] { "--start-fullscreen" }38 });39 var pages = await browser.PagesAsync();40 var page = pages.Single();41 return new YandexMapsClient(page);42 }43 static async Task<Y> Using<X, Y>(X elm, Func<X, Task<Y>> f) where X : JSHandle44 {45 try46 {47 return await f(elm);48 }49 finally50 {51 await elm.DisposeAsync();52 }53 }54 static Task<Unit> Using<X>(X elm, Func<X, Task> f) where X : JSHandle =>55 Using(elm, x => f(x).ToUnit());56 Task HideElements(params string[] selectors) => _page.EvaluateExpressionAsync(57 $"[{selectors.Map(x => '"' + x + '"').Apply(xs => string.Join(',', xs))}]" +58 ".map(x => [...document.querySelectorAll(x)]).reduce((x, y) => [...x, ...y]).filter(x => x != null).forEach(x => x.setAttribute('style', 'display:none'))"59 );60 async Task<Option<byte[]>> GetRoutesScreenshot()61 {62 await _page.EvaluateExpressionAsync(63 "[...document.querySelectorAll('.route-snippet-view')].forEach(x => x.classList.remove('_active'))"64 );65 await HideElements(...

Full Screen

Full Screen

Extensions.cs

Source:Extensions.cs Github

copy

Full Screen

...25 var newArgs = new object[args.Length + 1];26 newArgs[0] = elementHandle;27 args.CopyTo(newArgs, 1);28 var result = await elementHandle.ExecutionContext.EvaluateFunctionAsync<T>(pageFunction, newArgs);29 await elementHandle.DisposeAsync();30 return result;31 }32 /// <summary>33 /// 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)"/>34 /// </summary>35 /// <typeparam name="T"></typeparam>36 /// <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>37 /// <param name="pageFunction">Function to be evaluated in browser context</param>38 /// <param name="args">Arguments to pass to <c>pageFunction</c></param>39 /// <returns>Task which resolves to the return value of <c>pageFunction</c></returns>40 public static async Task<T> EvaluateFunctionAsync<T>(this Task<JSHandle> arrayHandleTask, string pageFunction, params object[] args)41 {42 var arrayHandle = await arrayHandleTask;43 var newArgs = new object[args.Length + 1];44 newArgs[0] = arrayHandle;45 args.CopyTo(newArgs, 1);46 var result = await arrayHandle.ExecutionContext.EvaluateFunctionAsync<T>(pageFunction, newArgs);47 await arrayHandle.DisposeAsync();48 return result;49 }50 }51}...

Full Screen

Full Screen

QueryObjectsTests.cs

Source:QueryObjectsTests.cs Github

copy

Full Screen

...24 [Fact]25 public async Task ShouldFailForDisposedHandles()26 {27 var prototypeHandle = await Page.EvaluateExpressionHandleAsync("HTMLBodyElement.prototype");28 await prototypeHandle.DisposeAsync();29 var exception = await Assert.ThrowsAsync<PuppeteerException>(()30 => Page.QueryObjectsAsync(prototypeHandle));31 Assert.Equal("Prototype JSHandle is disposed!", exception.Message);32 }33 [Fact]34 public async Task ShouldFailPrimitiveValuesAsPrototypes()35 {36 var prototypeHandle = await Page.EvaluateExpressionHandleAsync("42");37 var exception = await Assert.ThrowsAsync<PuppeteerException>(()38 => Page.QueryObjectsAsync(prototypeHandle));39 Assert.Equal("Prototype JSHandle must not be referencing primitive value", exception.Message);40 }41 }42}...

Full Screen

Full Screen

PuppeteerExtensions.cs

Source:PuppeteerExtensions.cs Github

copy

Full Screen

...25 }26 public static async Task WaitForTruth(this Page page, string script, WaitForFunctionOptions opts = null)27 {28 var jsHandle = await page.WaitForExpressionAsync(script, opts);29 await jsHandle.DisposeAsync();30 }31 public static async Task WaitForDocumentInteractiveState(this Page page, int? timeout = null)32 {33 await page.WaitForTruth("document.readyState === 'interactive' || document.readyState === 'complete'", new WaitForFunctionOptions { Timeout = timeout ?? page.Browser.DefaultWaitForTimeout });34 }35 }36}...

Full Screen

Full Screen

DisposeAsync

Using AI Code Generation

copy

Full Screen

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 = true });10 var page = await browser.NewPageAsync();11 var jsHandle = await page.EvaluateExpressionHandleAsync("() => { window.disposeMe = {a: 1}; return window.disposeMe; }");12 await jsHandle.DisposeAsync();13 await browser.CloseAsync();14 }15 }16}17 at PuppeteerSharp.JSHandle.ThrowIfDisposed()18 at PuppeteerSharp.JSHandle.DisposeAsync()19 at PuppeteerSharp.Program.Main(String[] args) in 2.cs:line 1520I have tried the latest version (5.0.2) and the DisposeAsync method is available, but the error is still the

Full Screen

Full Screen

DisposeAsync

Using AI Code Generation

copy

Full Screen

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 handle = await page.QuerySelectorAsync("body");13 await handle.DisposeAsync();14 await browser.CloseAsync();15 }16 }17}

Full Screen

Full Screen

DisposeAsync

Using AI Code Generation

copy

Full Screen

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 input = await page.QuerySelectorAsync("input[name='q']");13 var handle = await input.GetPropertyAsync("value");14 Console.WriteLine(await handle.JsonValueAsync());15 await handle.DisposeAsync();16 await browser.CloseAsync();17 }18 }19}

Full Screen

Full Screen

DisposeAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4using System.Threading;5{6 {7 public static async Task Main(string[] args)8 {9 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });10 var page = await browser.NewPageAsync();11 var elementHandle = await page.QuerySelectorAsync("input.gLFyf.gsfi");12 await elementHandle.TypeAsync("PuppeteerSharp");13 await elementHandle.DisposeAsync();14 await browser.CloseAsync();15 }16 }17}

Full Screen

Full Screen

DisposeAsync

Using AI Code Generation

copy

Full Screen

1var page = await browser.NewPageAsync();2var element = await page.QuerySelectorAsync("input[name='q']");3await element.TypeAsync("PuppeteerSharp");4await page.Keyboard.PressAsync("Enter");5await page.WaitForNavigationAsync();6await page.ScreenshotAsync("screenshot.png");7await page.CloseAsync();8var page = await browser.NewPageAsync();9var element = await page.QuerySelectorAsync("input[name='q']");10await element.TypeAsync("PuppeteerSharp");11await page.Keyboard.PressAsync("Enter");12await page.WaitForNavigationAsync();13await page.ScreenshotAsync("screenshot.png");14await page.CloseAsync();15var page = await browser.NewPageAsync();16var element = await page.QuerySelectorAsync("input[name='q']");17await element.TypeAsync("PuppeteerSharp");18await page.Keyboard.PressAsync("Enter");19await page.WaitForNavigationAsync();20await page.ScreenshotAsync("screenshot.png");21await page.CloseAsync();22var page = await browser.NewPageAsync();23var element = await page.QuerySelectorAsync("input[name='q']");24await element.TypeAsync("PuppeteerSharp");25await page.Keyboard.PressAsync("Enter");26await page.WaitForNavigationAsync();27await page.ScreenshotAsync("screenshot.png");28await page.CloseAsync();29var page = await browser.NewPageAsync();30var element = await page.QuerySelectorAsync("input[name='q']");31await element.TypeAsync("PuppeteerSharp");32await page.Keyboard.PressAsync("Enter");33await page.WaitForNavigationAsync();34await page.ScreenshotAsync("screenshot.png");35await page.CloseAsync();36var page = await browser.NewPageAsync();

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful