How to use OnClose method of PuppeteerSharp.Transport.WebSocketTransport class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Transport.WebSocketTransport.OnClose

Connection.cs

Source:Connection.cs Github

copy

Full Screen

...116 return session;117 }118 internal bool HasPendingCallbacks() => _callbacks.Count != 0;119 #endregion120 private void OnClose()121 {122 if (IsClosed)123 {124 return;125 }126 IsClosed = true;127 Transport.StopReading();128 Closed?.Invoke(this, new EventArgs());129 foreach (var session in _sessions.Values.ToArray())130 {131 session.OnClosed();132 }133 _sessions.Clear();134 foreach (var response in _callbacks.Values.ToArray())135 {136 response.TaskWrapper.TrySetException(new TargetClosedException(137 $"Protocol error({response.Method}): Target closed."138 ));139 }140 _callbacks.Clear();141 }142 internal static IConnection FromSession(CDPSession session)143 {144 var connection = session.Connection;145 while (connection is CDPSession)146 {147 connection = connection.Connection;148 }149 return connection;150 }151 #region Private Methods152 private async void Transport_MessageReceived(object sender, MessageReceivedEventArgs e)153 {154 var response = e.Message;155 JObject obj = null;156 if (response.Length > 0 && Delay > 0)157 {158 await Task.Delay(Delay).ConfigureAwait(false);159 }160 try161 {162 obj = JObject.Parse(response);163 }164 catch (JsonException exc)165 {166 _logger.LogError(exc, "Failed to deserialize response", response);167 return;168 }169 _logger.LogTrace("◀ Receive {Message}", response);170 var id = obj[MessageKeys.Id]?.Value<int>();171 if (id.HasValue)172 {173 //If we get the object we are waiting for we return if174 //if not we add this to the list, sooner or later some one will come for it 175 if (_callbacks.TryRemove(id.Value, out var callback))176 {177 if (obj[MessageKeys.Error] != null)178 {179 callback.TaskWrapper.TrySetException(new MessageException(callback, obj));180 }181 else182 {183 callback.TaskWrapper.TrySetResult(obj[MessageKeys.Result].Value<JObject>());184 }185 }186 }187 else188 {189 var method = obj[MessageKeys.Method].AsString();190 var param = obj[MessageKeys.Params];191 if (method == "Target.receivedMessageFromTarget")192 {193 var sessionId = param[MessageKeys.SessionId].AsString();194 if (_sessions.TryGetValue(sessionId, out var session))195 {196 session.OnMessage(param[MessageKeys.Message].AsString());197 }198 }199 else if (method == "Target.detachedFromTarget")200 {201 var sessionId = param[MessageKeys.SessionId].AsString();202 if (_sessions.TryRemove(sessionId, out var session) && !session.IsClosed)203 {204 session.OnClosed();205 }206 }207 else208 {209 MessageReceived?.Invoke(this, new MessageEventArgs210 {211 MessageID = method,212 MessageData = param213 });214 }215 }216 }217 void Transport_Closed(object sender, EventArgs e) => OnClose();218 #endregion219 #region Static Methods220 /// <summary>221 /// Gets default web socket factory implementation.222 /// </summary>223 public static readonly Func<Uri, IConnectionOptions, CancellationToken, Task<WebSocket>> DefaultWebSocketFactory = async (uri, options, cancellationToken) =>224 {225 var result = new ClientWebSocket();226 result.Options.KeepAliveInterval = TimeSpan.Zero;227 await result.ConnectAsync(uri, cancellationToken).ConfigureAwait(false);228 return result;229 };230 internal static async Task<Connection> Create(string url, IConnectionOptions connectionOptions, ILoggerFactory loggerFactory = null)231 {232 var transport = connectionOptions.Transport;233 if (transport == null)234 {235 var ws = await (connectionOptions.WebSocketFactory ?? DefaultWebSocketFactory)(236 new Uri(url),237 connectionOptions,238 default).ConfigureAwait(false);239 transport = new WebSocketTransport(ws, connectionOptions.EnqueueTransportMessages);240 }241 return new Connection(url, connectionOptions.SlowMo, transport, loggerFactory);242 }243 /// <summary>244 /// Releases all resource used by the <see cref="Connection"/> object.245 /// It will raise the <see cref="Closed"/> event and dispose <see cref="Transport"/>.246 /// </summary>247 /// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="Connection"/>. The248 /// <see cref="Dispose"/> method leaves the <see cref="Connection"/> in an unusable state.249 /// After calling <see cref="Dispose"/>, you must release all references to the250 /// <see cref="Connection"/> so the garbage collector can reclaim the memory that the251 /// <see cref="Connection"/> was occupying.</remarks>252 public void Dispose()253 {254 OnClose();255 Transport.Dispose();256 }257 #endregion258 #region IConnection259 ILoggerFactory IConnection.LoggerFactory => LoggerFactory;260 bool IConnection.IsClosed => IsClosed;261 Task<JObject> IConnection.SendAsync(string method, dynamic args, bool waitForCallback)262 => SendAsync(method, args, waitForCallback);263 IConnection IConnection.Connection => null;264 #endregion265 }266}...

Full Screen

Full Screen

WebSocketTransport.cs

Source:WebSocketTransport.cs Github

copy

Full Screen

...67 while (true)68 {69 if (IsClosed)70 {71 OnClose();72 return null;73 }74 var endOfMessage = false;75 var response = new StringBuilder();76 while (!endOfMessage)77 {78 WebSocketReceiveResult result;79 try80 {81 result = await _client.ReceiveAsync(82 new ArraySegment<byte>(buffer),83 _readerCancellationSource.Token).ConfigureAwait(false);84 }85 catch (OperationCanceledException)86 {87 return null;88 }89 catch (Exception)90 {91 OnClose();92 return null;93 }94 endOfMessage = result.EndOfMessage;95 if (result.MessageType == WebSocketMessageType.Text)96 {97 response.Append(Encoding.UTF8.GetString(buffer, 0, result.Count));98 }99 else if (result.MessageType == WebSocketMessageType.Close)100 {101 OnClose();102 return null;103 }104 }105 MessageReceived?.Invoke(this, new MessageReceivedEventArgs(response.ToString()));106 }107 }108 private void OnClose()109 {110 Closed?.Invoke(this, EventArgs.Empty);111 IsClosed = true;112 }113 /// <inheritdoc/>114 public void Dispose() => _client?.Dispose();115 }116}...

Full Screen

Full Screen

OnClose

Using AI Code Generation

copy

Full Screen

1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",4 Args = new string[] { "--start-maximized" }5});6var page = await browser.NewPageAsync();7await page.WaitForTimeoutAsync(10000);8await browser.CloseAsync();9var browser = await Puppeteer.LaunchAsync(new LaunchOptions10{11 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",12 Args = new string[] { "--start-maximized" }13});14var page = await browser.NewPageAsync();15await page.WaitForTimeoutAsync(10000);16await browser.CloseAsync();17var browser = await Puppeteer.LaunchAsync(new LaunchOptions18{19 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",20 Args = new string[] { "--start-maximized" }21});22var page = await browser.NewPageAsync();23await page.WaitForTimeoutAsync(10000);24await browser.CloseAsync();25var browser = await Puppeteer.LaunchAsync(new LaunchOptions26{27 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",28 Args = new string[] { "--start-maximized" }29});30var page = await browser.NewPageAsync();31await page.WaitForTimeoutAsync(10000);32await browser.CloseAsync();33var browser = await Puppeteer.LaunchAsync(new LaunchOptions34{

Full Screen

Full Screen

OnClose

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 browserFetcher = new BrowserFetcher();9 var revisionInfo = browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision).Result;10 var browser = await Puppeteer.LaunchAsync(new LaunchOptions11 {12 });13 var page = await browser.NewPageAsync();14 await page.ScreenshotAsync("google.png");15 await browser.CloseAsync();16 }17 }18}19The problem is that the OnClose method of the WebSocketTransport class is never called. I tried to call the browser.CloseAsync() method but it doesn't seem to work. Any ideas what I'm doing wrong?

Full Screen

Full Screen

OnClose

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 Args = new string[] { "--no-sandbox" }11 });12 browser.Transport.OnClose += Transport_OnClose;13 var page = await browser.NewPageAsync();14 await Task.Delay(10000);15 await browser.CloseAsync();16 }17 private static void Transport_OnClose(object sender, EventArgs e)18 {19 Console.WriteLine("Browser closed");20 }21 }22}23using System;24using System.Threading.Tasks;25using PuppeteerSharp;26{27 {28 static async Task Main(string[] args)29 {30 var browser = await Puppeteer.LaunchAsync(new LaunchOptions31 {32 Args = new string[] { "--no-sandbox" }33 });34 browser.OnClose += Browser_OnClose;35 var page = await browser.NewPageAsync();36 await Task.Delay(10000);37 await browser.CloseAsync();38 }39 private static void Browser_OnClose(object sender, EventArgs e)40 {41 Console.WriteLine("Browser closed");42 }43 }44}45using System;46using System.Threading.Tasks;47using PuppeteerSharp;48{

Full Screen

Full Screen

OnClose

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 Console.WriteLine("Hello World!");9 {10 Args = new string[] { "--no-sandbox", "--disable-setuid-sandbox" }11 };12 var browser = await Puppeteer.LaunchAsync(options);13 var page = await browser.NewPageAsync();14 await page.ScreenshotAsync("test.png");15 await browser.CloseAsync();16 Console.WriteLine("Done");17 }18 }19}

Full Screen

Full Screen

OnClose

Using AI Code Generation

copy

Full Screen

1var connection = new Connection(transport);2await connection.SendAsync("Target.closeTarget", new { targetId = "0d8d5a5a-4f0d-4c5d-8c2d-5f5a5a5a5a5a" });3await transport.OnClose;4var connection = new Connection(transport);5await connection.SendAsync("Target.closeTarget", new { targetId = "0d8d5a5a-4f0d-4c5d-8c2d-5f5a5a5a5a5a" });6await transport.OnClose;7var connection = new Connection(transport);8await connection.SendAsync("Target.closeTarget", new { targetId = "0d8d5a5a-4f0d-4c5d-8c2d-5f5a5a5a5a5a" });9await transport.OnClose;

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