Best Puppeteer-sharp code snippet using PuppeteerSharp.Connection.Dispose
Browser.cs
Source:Browser.cs
...218 => (await Connection.SendAsync<BrowserGetVersionResponse>("Browser.getVersion").ConfigureAwait(false)).UserAgent;219 /// <summary>220 /// Disconnects Puppeteer from the browser, but leaves the process running. After calling <see cref="Disconnect"/>, the browser object is considered disposed and cannot be used anymore221 /// </summary>222 public void Disconnect() => Connection.Dispose();223 /// <summary>224 /// Closes Chromium and all of its pages (if any were opened). The browser object itself is considered disposed and cannot be used anymore225 /// </summary>226 /// <returns>Task</returns>227 public Task CloseAsync() => _closeTask ?? (_closeTask = CloseCoreAsync());228 /// <summary>229 /// This searches for a target in this specific browser context.230 /// <example>231 /// <code>232 /// <![CDATA[233 /// await page.EvaluateAsync("() => window.open('https://www.example.com/')");234 /// var newWindowTarget = await browserContext.WaitForTargetAsync((target) => target.Url == "https://www.example.com/");235 /// ]]>236 /// </code>237 /// </example>238 /// </summary>239 /// <param name="predicate">A function to be run for every target</param>240 /// <param name="options">options</param>241 /// <returns>Resolves to the first target found that matches the predicate function.</returns>242 public async Task<Target> WaitForTargetAsync(Func<Target, bool> predicate, WaitForOptions options = null)243 {244 int timeout = options?.Timeout ?? DefaultWaitForTimeout;245 var existingTarget = Targets().FirstOrDefault(predicate);246 if (existingTarget != null)247 {248 return existingTarget;249 }250 var targetCompletionSource = new TaskCompletionSource<Target>(TaskCreationOptions.RunContinuationsAsynchronously);251 void TargetHandler(object sender, TargetChangedArgs e)252 {253 if (predicate(e.Target))254 {255 targetCompletionSource.TrySetResult(e.Target);256 }257 }258 try259 {260 TargetCreated += TargetHandler;261 TargetChanged += TargetHandler;262 return await targetCompletionSource.Task.WithTimeout(timeout).ConfigureAwait(false);263 }264 finally265 {266 TargetCreated -= TargetHandler;267 TargetChanged -= TargetHandler;268 }269 }270 private async Task CloseCoreAsync()271 {272 try273 {274 try275 {276 // Initiate graceful browser close operation but don't await it just yet,277 // because we want to ensure process shutdown first.278 var browserCloseTask = Connection.IsClosed279 ? Task.CompletedTask280 : Connection.SendAsync("Browser.close", null);281 if (Launcher != null)282 {283 // Notify process that exit is expected, but should be enforced if it284 // doesn't occur withing the close timeout.285 var closeTimeout = TimeSpan.FromMilliseconds(CloseTimeout);286 await Launcher.EnsureExitAsync(closeTimeout).ConfigureAwait(false);287 }288 // Now we can safely await the browser close operation without risking keeping chromium289 // process running for indeterminate period.290 await browserCloseTask.ConfigureAwait(false);291 }292 finally293 {294 Disconnect();295 }296 }297 catch (Exception)298 {299 if (Launcher != null)300 {301 await Launcher.KillAsync().ConfigureAwait(false);302 }303 }304 // Ensure that remaining targets are always marked closed, so that asynchronous page close305 // operations on any associated pages don't get blocked.306 foreach (var target in TargetsMap.Values)307 {308 target.CloseTaskWrapper.TrySetResult(false);309 }310 Closed?.Invoke(this, new EventArgs());311 }312 #endregion313 #region Private Methods314 internal void ChangeTarget(Target target)315 {316 var args = new TargetChangedArgs { Target = target };317 TargetChanged?.Invoke(this, args);318 target.BrowserContext.OnTargetChanged(this, args);319 }320 internal async Task<Page> CreatePageInContextAsync(string contextId)321 {322 var createTargetRequest = new TargetCreateTargetRequest323 {324 Url = "about:blank"325 };326 if (contextId != null)327 {328 createTargetRequest.BrowserContextId = contextId;329 }330 string targetId = (await Connection.SendAsync<TargetCreateTargetResponse>("Target.createTarget", createTargetRequest)331 .ConfigureAwait(false)).TargetId;332 var target = TargetsMap[targetId];333 await target.InitializedTask.ConfigureAwait(false);334 return await target.PageAsync().ConfigureAwait(false);335 }336 internal async Task DisposeContextAsync(string contextId)337 {338 await Connection.SendAsync("Target.disposeBrowserContext", new TargetDisposeBrowserContextRequest339 {340 BrowserContextId = contextId341 }).ConfigureAwait(false);342 _contexts.Remove(contextId);343 }344 private async void Connection_Disconnected(object sender, EventArgs e)345 {346 try347 {348 await CloseAsync().ConfigureAwait(false);349 Disconnected?.Invoke(this, new EventArgs());350 }351 catch (Exception ex)352 {353 string message = $"Browser failed to process Connection Close. {ex.Message}. {ex.StackTrace}";354 Connection.Close(message);355 }356 }357 private async void Connect_MessageReceived(object sender, MessageEventArgs e)358 {359 try360 {361 switch (e.MessageID)362 {363 case "Target.targetCreated":364 await CreateTargetAsync(e.MessageData.ToObject<TargetCreatedResponse>(true)).ConfigureAwait(false);365 return;366 case "Target.targetDestroyed":367 await DestroyTargetAsync(e.MessageData.ToObject<TargetDestroyedResponse>(true)).ConfigureAwait(false);368 return;369 case "Target.targetInfoChanged":370 ChangeTargetInfo(e.MessageData.ToObject<TargetCreatedResponse>(true));371 return;372 }373 }374 catch (Exception ex)375 {376 string message = $"Browser failed to process {e.MessageID}. {ex.Message}. {ex.StackTrace}";377 Connection.Close(message);378 }379 }380 private void ChangeTargetInfo(TargetCreatedResponse e)381 {382 if (!TargetsMap.ContainsKey(e.TargetInfo.TargetId))383 {384 throw new InvalidTargetException("Target should exists before ChangeTargetInfo");385 }386 var target = TargetsMap[e.TargetInfo.TargetId];387 target.TargetInfoChanged(e.TargetInfo);388 }389 private async Task DestroyTargetAsync(TargetDestroyedResponse e)390 {391 if (!TargetsMap.ContainsKey(e.TargetId))392 {393 throw new InvalidTargetException("Target should exists before DestroyTarget");394 }395 var target = TargetsMap[e.TargetId];396 TargetsMap.Remove(e.TargetId);397 target.CloseTaskWrapper.TrySetResult(true);398 if (await target.InitializedTask.ConfigureAwait(false))399 {400 var args = new TargetChangedArgs { Target = target };401 TargetDestroyed?.Invoke(this, args);402 target.BrowserContext.OnTargetDestroyed(this, args);403 }404 }405 private async Task CreateTargetAsync(TargetCreatedResponse e)406 {407 var targetInfo = e.TargetInfo;408 string browserContextId = targetInfo.BrowserContextId;409 if (!(browserContextId != null && _contexts.TryGetValue(browserContextId, out var context)))410 {411 context = DefaultContext;412 }413 var target = new Target(414 e.TargetInfo,415 () => Connection.CreateSessionAsync(targetInfo),416 context);417 TargetsMap[e.TargetInfo.TargetId] = target;418 if (await target.InitializedTask.ConfigureAwait(false))419 {420 var args = new TargetChangedArgs { Target = target };421 TargetCreated?.Invoke(this, args);422 context.OnTargetCreated(this, args);423 }424 }425 internal static async Task<Browser> CreateAsync(426 Connection connection,427 string[] contextIds,428 bool ignoreHTTPSErrors,429 ViewPortOptions defaultViewPort,430 LauncherBase launcher)431 {432 var browser = new Browser(connection, contextIds, ignoreHTTPSErrors, defaultViewPort, launcher);433 await connection.SendAsync("Target.setDiscoverTargets", new TargetSetDiscoverTargetsRequest434 {435 Discover = true436 }).ConfigureAwait(false);437 return browser;438 }439 #endregion440 #region IDisposable441 /// <inheritdoc />442 public void Dispose()443 {444 Dispose(true);445 GC.SuppressFinalize(this);446 }447 /// <summary>448 /// Closes <see cref="Connection"/> and any Chromium <see cref="Process"/> that was449 /// created by Puppeteer.450 /// </summary>451 /// <param name="disposing">Indicates whether disposal was initiated by <see cref="Dispose()"/> operation.</param>452 protected virtual void Dispose(bool disposing) => _ = CloseAsync();453 #endregion454 }455}...
Connection.cs
Source:Connection.cs
...241 }242 return new Connection(url, connectionOptions.SlowMo, transport);243 }244 /// <inheritdoc />245 public void Dispose()246 {247 Dispose(true);248 GC.SuppressFinalize(this);249 }250 /// <summary>251 /// Releases all resource used by the <see cref="Connection"/> object.252 /// It will raise the <see cref="Disconnected"/> event and dispose <see cref="Transport"/>.253 /// </summary>254 /// <remarks>Call <see cref="Dispose()"/> when you are finished using the <see cref="Connection"/>. The255 /// <see cref="Dispose()"/> method leaves the <see cref="Connection"/> in an unusable state.256 /// After calling <see cref="Dispose()"/>, you must release all references to the257 /// <see cref="Connection"/> so the garbage collector can reclaim the memory that the258 /// <see cref="Connection"/> was occupying.</remarks>259 /// <param name="disposing">Indicates whether disposal was initiated by <see cref="Dispose()"/> operation.</param>260 protected virtual void Dispose(bool disposing)261 {262 Close("Connection disposed");263 Transport.Dispose();264 }265 #endregion266 }267}...
WebSocketTransport.cs
Source:WebSocketTransport.cs
...107 {108 // Asynchronous read operations may still be in progress, so cancel it first and then dispose109 // the associated CancellationTokenSource.110 readerCts.Cancel();111 readerCts.Dispose();112 }113 }114 /// <inheritdoc/>115 public void Dispose()116 {117 Dispose(true);118 GC.SuppressFinalize(this);119 }120 /// <summary>121 /// Close the WebSocketTransport122 /// </summary>123 /// <param name="disposing">Indicates whether disposal was initiated by <see cref="Dispose()"/> operation.</param>124 protected virtual void Dispose(bool disposing)125 {126 // Make sure any outstanding asynchronous read operation is cancelled.127 StopReading();128 _client?.Dispose();129 }130 #endregion131 #region Private methods132 /// <summary>133 /// Starts listening the socket134 /// </summary>135 /// <returns>The start.</returns>136 private async Task<object> GetResponseAsync(CancellationToken cancellationToken)137 {138 var buffer = new byte[2048];139 while (!IsClosed)140 {141 var endOfMessage = false;142 var response = new StringBuilder();...
JSHandle.cs
Source:JSHandle.cs
...26 /// <summary>27 /// Gets or sets a value indicating whether this <see cref="JSHandle"/> is disposed.28 /// </summary>29 /// <value><c>true</c> if disposed; otherwise, <c>false</c>.</value>30 public bool Disposed { get; private set; }31 /// <summary>32 /// Gets or sets the remote object.33 /// </summary>34 /// <value>The remote object.</value>35 public JToken RemoteObject { get; }36 /// <summary>37 /// Gets the client.38 /// </summary>39 /// <value>The client.</value>40 protected CDPSession Client { get; }41 /// <summary>42 /// Gets the logger.43 /// </summary>44 /// <value>The logger.</value>45 protected ILogger Logger { get; }46 /// <summary>47 /// Fetches a single property from the referenced object48 /// </summary>49 /// <param name="propertyName">property to get</param>50 /// <returns>Task of <see cref="JSHandle"/></returns>51 public async Task<JSHandle> GetPropertyAsync(string propertyName)52 {53 var objectHandle = await ExecutionContext.EvaluateFunctionHandleAsync(@"(object, propertyName) => {54 const result = { __proto__: null};55 result[propertyName] = object[propertyName];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];145 return "JSHandle@" + type;146 }147 return "JSHandle:" + RemoteObjectHelper.ValueFromRemoteObject<object>(RemoteObject)?.ToString();148 }149 internal object FormatArgument(ExecutionContext context)150 {151 if (ExecutionContext != context)152 {153 throw new PuppeteerException("JSHandles can be evaluated only in the context they were created!");154 }155 if (Disposed)156 {157 throw new PuppeteerException("JSHandle is disposed!");158 }159 var unserializableValue = RemoteObject[MessageKeys.UnserializableValue];160 if (unserializableValue != null)161 {162 return unserializableValue;163 }164 if (RemoteObject[MessageKeys.ObjectId] == null)165 {166 var value = RemoteObject[MessageKeys.Value];167 return new { value };168 }169 var objectId = RemoteObject[MessageKeys.ObjectId];...
PuppeteerEngine.cs
Source:PuppeteerEngine.cs
...168 return;169 if (_browser != null && !_browser.IsClosed)170 {171 await _browser.CloseAsync();172 _browser.Dispose();173 _browser = null;174 }175 }176 public void Dispose()177 {178 if (_remoteBrowserAddress != null)179 return;180 _logger.Debug("Disposing puppeteer engine");181 _browser?.Dispose();182 }183 }184}...
AbilityImageService.cs
Source:AbilityImageService.cs
...53 }54 finally55 {56 await browser.CloseAsync();57 await browser.DisposeAsync();58 }59 }60 private async Task<Stream> GetWikiCard(string id)61 {62 var abilityId = int.Parse(id);63 var collection = this.metaClient.GetAbilities();64 var ability = collection.FirstOrDefault(_ => _.Id == abilityId);65 if (ability is null)66 throw new UserFriendlyException($"Unable to find ability {id}");67 var hero = this.metaClient.GetHero(ability.HeroId);68 if(hero is null)69 throw new UserFriendlyException($"Unable to find hero {ability.HeroId}");70 var browser = await Puppeteer.ConnectAsync(this.puppeteerConfuration);71 try72 {73 var page = await browser.NewPageAsync();74 page.DefaultNavigationTimeout = 0;75 await page.SetViewportAsync(new ViewPortOptions { Width = 1920, Height = 1080 });76 var slug = hero.Name.Replace(" ", "_");77 if (slug == "Invoker") slug = "Invoker/Ability_Draft";78 await page.GoToAsync($"https://dota2.fandom.com/wiki/{slug}");79 await Task.Delay(TimeSpan.FromSeconds(5));80 var elements = await page.QuerySelectorAllAsync(".ability-background");81 var element = await GetElement(elements, ability.Name);82 var stream = await element.ScreenshotStreamAsync(new ScreenshotOptions() { Type = ScreenshotType.Png });83 return stream;84 }85 finally86 {87 await browser.CloseAsync();88 await browser.DisposeAsync();89 }90 }91 private static async Task<ElementHandle> GetElement(ElementHandle[] elements, string name)92 {93 foreach (var element in elements)94 {95 var property = await element.GetPropertyAsync("innerText");96 var body = await property.JsonValueAsync<string>();97 var title = body.Split("\n").FirstOrDefault();98 if (title == name)99 return element;100 else101 continue;102 }...
Crawler.cs
Source:Crawler.cs
...66 if (response?.Ok ?? false)67 doc.LoadHtml(await page.GetContentAsync());68 else69 {70 this.Dispose();71 Exceptions.BadOrNoResponseException badResponseException;72 if (response == null)73 badResponseException = new("There is no response from server. Please check your connection.");74 else 75 badResponseException = new(response.StatusText);76 throw badResponseException;77 }78 await ResolvePlaces(token);79 }80 private Task ResolvePlaces(CancellationToken token)81 {82 while(true && !token.IsCancellationRequested)83 {84 if (isFirstPage)85 {86 var match = Regex.Match(page.Url, _UrlRegex);87 var lat = match.Groups["lat"].Value;88 var lon = match.Groups["lon"].Value;89 if (double.TryParse(lat, out var tempLat) && double.TryParse(lon, out var tempLon))90 {91 sourceLat = tempLat;92 sourceLon = tempLon;93 }94 isFirstPage = false;95 }96 var names = doc.DocumentNode.SelectNodes("//h3[contains(@class, 'section-result-title')]");97 var results = doc.DocumentNode.SelectNodes("//*[@id='pane']/div/div[1]/div/div/div[4]/div[1]/div[contains(@class, 'section-result')]");98 for (var i = 0; i < results.Count; i++)99 {100 }101 }102 if(token.IsCancellationRequested)103 Dispose();104 return Task.CompletedTask;105 }106#pragma warning disable CA1816 // Dispose methods should call SuppressFinalize107 public void Dispose()108#pragma warning restore CA1816 // Dispose methods should call SuppressFinalize109 {110 browser.Dispose();111 }112}...
RanksImageService.cs
Source:RanksImageService.cs
...42 await page.Keyboard.TypeAsync(streamId.ToString());43 await page.WaitForSelectorAsync("#ratings-graph");44 var element = await page.QuerySelectorAsync("#ratings-graph");45 var stream = await element.ScreenshotStreamAsync(new ScreenshotOptions() { Type = ScreenshotType.Png });46 await element.DisposeAsync();47 await page.DisposeAsync();48 var id = Guid.NewGuid();49 var client = new BlobClient(this.connectionString, CONTAINER_NAME, $"{id}.png");50 await client.UploadAsync(stream);51 return client.Uri;52 }53 catch(Exception)54 {55 return null;56 }57 finally58 {59 await browser.CloseAsync();60 await browser.DisposeAsync();61 }62 }63 }64}...
Dispose
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var client = await connection.CreateCDPSessionAsync();9 await client.SendAsync("Page.enable");10 var page = await client.Target.PageAsync();11 await page.GoToAsync("
Dispose
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.ConnectAsync(new ConnectOptions9 {
Dispose
Using AI Code Generation
1connection.Dispose();2page.Dispose();3browser.Dispose();4fetcher.Dispose();5context.Dispose();6target.Dispose();7frame.Dispose();8dialog.Dispose();9element.Dispose();10handle.Dispose();11handle.Dispose();12keyboard.Dispose();13mouse.Dispose();14touchscreen.Dispose();
Dispose
Using AI Code Generation
1{2 var session = connection.CreateSession();3 Console.WriteLine(response);4}5using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))6{7 var page = await browser.NewPageAsync();8 Console.WriteLine(page.Url);9}10using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))11{12 var page = await browser.NewPageAsync();13 Console.WriteLine(page.Url);14}15var browserFetcher = new BrowserFetcher();16await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);17Console.WriteLine(browserFetcher.LocalRevisions().First());18using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))19{20 var page = await browser.NewPageAsync();21 Console.WriteLine(page.Url);22}23using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))24{25 var page = await browser.NewPageAsync();26 Console.WriteLine(page.Url);27}28using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))29{30 var page = await browser.NewPageAsync();31 Console.WriteLine(page.Url);32}33using (var browser = await Puppeteer.LaunchAsync(new
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!!