Best Puppeteer-sharp code snippet using PuppeteerSharp.MessageEventArgs
Connection.cs
Source:Connection.cs
...59 public event EventHandler Closed;60 /// <summary>61 /// Occurs when a message from chromium is received.62 /// </summary>63 public event EventHandler<MessageEventArgs> MessageReceived;64 /// <summary>65 /// Gets or sets a value indicating whether this <see cref="Connection"/> is closed.66 /// </summary>67 /// <value><c>true</c> if is closed; otherwise, <c>false</c>.</value>68 public bool IsClosed { get; internal set; }69 /// <summary>70 /// Gets the logger factory.71 /// </summary>72 /// <value>The logger factory.</value>73 public ILoggerFactory LoggerFactory { get; }74 #endregion75 #region Public Methods76 internal async Task<JObject> SendAsync(string method, dynamic args = null, bool waitForCallback = true)77 {78 if (IsClosed)79 {80 throw new TargetClosedException($"Protocol error({method}): Target closed.");81 }82 var id = Interlocked.Increment(ref _lastId);83 var message = JsonConvert.SerializeObject(new Dictionary<string, object>84 {85 { MessageKeys.Id, id },86 { MessageKeys.Method, method },87 { MessageKeys.Params, args }88 });89 _logger.LogTrace("Send ⺠{Id} Method {Method} Params {@Params}", id, method, (object)args);90 MessageTask callback = null;91 if (waitForCallback)92 {93 callback = new MessageTask94 {95 TaskWrapper = new TaskCompletionSource<JObject>(),96 Method = method97 };98 _callbacks[id] = callback;99 }100 await Transport.SendAsync(message).ConfigureAwait(false);101 return waitForCallback ? await callback.TaskWrapper.Task.ConfigureAwait(false) : null;102 }103 internal async Task<T> SendAsync<T>(string method, dynamic args = null)104 {105 JToken response = await SendAsync(method, args).ConfigureAwait(false);106 return response.ToObject<T>();107 }108 internal async Task<CDPSession> CreateSessionAsync(TargetInfo targetInfo)109 {110 var sessionId = (await SendAsync("Target.attachToTarget", new111 {112 targetId = targetInfo.TargetId113 }).ConfigureAwait(false))[MessageKeys.SessionId].AsString();114 var session = new CDPSession(this, targetInfo.Type, sessionId);115 _sessions.TryAdd(sessionId, session);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) =>...
CDPSession.cs
Source:CDPSession.cs
...63 internal Connection Connection { get; private set; }64 /// <summary>65 /// Occurs when message received from Chromium.66 /// </summary>67 public event EventHandler<MessageEventArgs> MessageReceived;68 /// <summary>69 /// Occurs when the connection is closed.70 /// </summary>71 public event EventHandler Disconnected;72 /// <summary>73 /// Gets or sets a value indicating whether this <see cref="CDPSession"/> is closed.74 /// </summary>75 /// <value><c>true</c> if is closed; otherwise, <c>false</c>.</value>76 public bool IsClosed { get; internal set; }77 /// <summary>78 /// Connection close reason.79 /// </summary>80 public string CloseReason { get; private set; }81 /// <summary>82 /// Gets the logger factory.83 /// </summary>84 /// <value>The logger factory.</value>85 #endregion86 #region Public Methods87 internal void Send(string method, object args = null)88 => _ = SendAsync(method, args, false);89 /// <summary>90 /// Protocol methods can be called with this method.91 /// </summary>92 /// <param name="method">The method name</param>93 /// <param name="args">The method args</param>94 /// <typeparam name="T">Return type.</typeparam>95 /// <returns>The task.</returns>96 public async Task<T> SendAsync<T>(string method, object args = null)97 {98 var content = await SendAsync(method, args).ConfigureAwait(false);99 return content.ToObject<T>(true);100 }101 /// <summary>102 /// Protocol methods can be called with this method.103 /// </summary>104 /// <param name="method">The method name</param>105 /// <param name="args">The method args</param>106 /// <param name="waitForCallback">107 /// If <c>true</c> the method will return a task to be completed when the message is confirmed by Chromium.108 /// If <c>false</c> the task will be considered complete after sending the message to Chromium.109 /// </param>110 /// <returns>The task.</returns>111 /// <exception cref="PuppeteerSharp.PuppeteerException"></exception>112 public async Task<JObject> SendAsync(string method, object args = null, bool waitForCallback = true)113 {114 if (Connection == null)115 {116 throw new PuppeteerException(117 $"Protocol error ({method}): Session closed. " +118 $"Most likely the {TargetType} has been closed." +119 $"Close reason: {CloseReason}");120 }121 var id = Connection.GetMessageID();122 MessageTask callback = null;123 if (waitForCallback)124 {125 callback = new MessageTask126 {127 TaskWrapper = new TaskCompletionSource<JObject>(),128 Method = method129 };130 _callbacks[id] = callback;131 }132 try133 {134 await Connection.RawSendASync(id, method, args, SessionId).ConfigureAwait(false);135 }136 catch (Exception ex)137 {138 if (waitForCallback && _callbacks.TryRemove(id, out _))139 {140 callback.TaskWrapper.TrySetException(new MessageException(ex.Message, ex));141 }142 }143 return waitForCallback ? await callback.TaskWrapper.Task.ConfigureAwait(false) : null;144 }145 /// <summary>146 /// Detaches session from target. Once detached, session won't emit any events and can't be used to send messages.147 /// </summary>148 /// <returns></returns>149 /// <exception cref="T:PuppeteerSharp.PuppeteerException"></exception>150 public Task DetachAsync()151 {152 if (Connection == null)153 {154 throw new PuppeteerException($"Session already detached.Most likely the {TargetType} has been closed.");155 }156 return Connection.SendAsync("Target.detachFromTarget", new TargetDetachFromTargetRequest157 {158 SessionId = SessionId159 });160 }161 internal bool HasPendingCallbacks() => _callbacks.Count != 0;162 #endregion163 #region Private Methods164 internal void OnMessage(ConnectionResponse obj)165 {166 var id = obj.Id;167 if (id.HasValue && _callbacks.TryRemove(id.Value, out var callback))168 {169 if (obj.Error != null)170 {171 callback.TaskWrapper.TrySetException(new MessageException(callback, obj.Error));172 }173 else174 {175 callback.TaskWrapper.TrySetResult(obj.Result);176 }177 }178 else179 {180 var method = obj.Method;181 var param = obj.Params?.ToObject<ConnectionResponseParams>();182 MessageReceived?.Invoke(this, new MessageEventArgs183 {184 MessageID = method,185 MessageData = obj.Params186 });187 }188 }189 internal void Close(string closeReason)190 {191 if (IsClosed)192 {193 return;194 }195 CloseReason = closeReason;196 IsClosed = true;...
FrameManager.cs
Source:FrameManager.cs
...31 internal Dictionary<string, Frame> Frames { get; set; }32 internal Frame MainFrame { get; set; }33 #endregion34 #region Private Methods35 void _client_MessageReceived(object sender, PuppeteerSharp.MessageEventArgs e)36 {37 switch (e.MessageID)38 {39 case "Page.frameAttached":40 OnFrameAttached(e.MessageData.frameId.ToString(), e.MessageData.parentFrameId.ToString());41 break;42 case "Page.frameNavigated":43 OnFrameNavigated(((JObject)e.MessageData.frame).ToObject<FramePayload>());44 break;45 case "Page.frameDetached":46 OnFrameDetached(e.MessageData.frameId.ToString());47 break;48 case "Runtime.executionContextCreated":49 OnExecutionContextCreated(new ContextPayload(e.MessageData.context));50 break;51 case "Runtime.executionContextDestroyed":52 OnExecutionContextDestroyed((int)e.MessageData.executionContextId);53 break;54 case "Runtime.executionContextsCleared":55 OnExecutionContextsCleared();56 break;57 case "Page.lifecycleEvent":58 OnLifeCycleEvent(e);59 break;60 default:61 break;62 }63 }64 private void OnLifeCycleEvent(MessageEventArgs e)65 {66 if (Frames.ContainsKey(e.MessageData.frameId.ToString()))67 {68 Frame frame = Frames[e.MessageData.frameId.ToString()];69 frame.OnLifecycleEvent(e.MessageData.loaderId.ToString(), e.MessageData.name.ToString());70 LifecycleEvent?.Invoke(this, new FrameEventArgs(frame));71 }72 }73 private void OnExecutionContextsCleared()74 {75 foreach (var context in _contextIdToContext.Values)76 {77 RemoveContext(context);78 }...
Worker.cs
Source:Worker.cs
...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 {93 switch (e.MessageID)94 {95 case "Runtime.executionContextCreated":96 OnExecutionContextCreated(e);97 break;98 case "Runtime.consoleAPICalled":99 await OnConsoleAPICalled(e).ConfigureAwait(false);100 break;101 case "Runtime.exceptionThrown":102 OnExceptionThrown(e);103 break;104 }105 }106 private void OnExceptionThrown(MessageEventArgs e)107 => _exceptionThrown(e.MessageData.SelectToken(MessageKeys.ExceptionDetails).ToObject<EvaluateExceptionDetails>());108 private async Task OnConsoleAPICalled(MessageEventArgs e)109 {110 var consoleData = e.MessageData.ToObject<PageConsoleResponse>();111 await _consoleAPICalled(112 consoleData.Type,113 consoleData.Args.Select<dynamic, JSHandle>(i => _jsHandleFactory(_executionContext, i)).ToArray())114 .ConfigureAwait(false);115 }116 private void OnExecutionContextCreated(MessageEventArgs e)117 {118 if (_jsHandleFactory == null)119 {120 _jsHandleFactory = (ctx, remoteObject) => new JSHandle(ctx, _client, remoteObject);121 _executionContext = new ExecutionContext(122 _client,123 e.MessageData.SelectToken(MessageKeys.Context).ToObject<ContextPayload>(),124 null);125 _executionContextCallback.TrySetResult(_executionContext);126 }127 }128 }129}...
CSSCoverage.cs
Source:CSSCoverage.cs
...85 });86 }87 return coverage.ToArray();88 }89 private async void client_MessageReceived(object sender, MessageEventArgs e)90 {91 switch (e.MessageID)92 {93 case "CSS.styleSheetAdded":94 await OnStyleSheetAdded(e.MessageData.ToObject<CSSStyleSheetAddedResponse>()).ConfigureAwait(false);95 break;96 case "Runtime.executionContextsCleared":97 OnExecutionContextsCleared();98 break;99 }100 }101 private async Task OnStyleSheetAdded(CSSStyleSheetAddedResponse styleSheetAddedResponse)102 {103 if (string.IsNullOrEmpty(styleSheetAddedResponse.Header.SourceURL))...
JSCoverage.cs
Source:JSCoverage.cs
...82 });83 }84 return coverage.ToArray();85 }86 private async void client_MessageReceived(object sender, MessageEventArgs e)87 {88 switch (e.MessageID)89 {90 case "Debugger.scriptParsed":91 await OnScriptParsed(e.MessageData.ToObject<DebuggerScriptParsedResponse>()).ConfigureAwait(false);92 break;93 case "Runtime.executionContextsCleared":94 OnExecutionContextsCleared();95 break;96 }97 }98 private async Task OnScriptParsed(DebuggerScriptParsedResponse scriptParseResponse)99 {100 if (scriptParseResponse.Url == ExecutionContext.EvaluationScriptUrl ||...
PuppeteerBaseTest.cs
Source:PuppeteerBaseTest.cs
...27 }28 protected static Task<dynamic> WaitForEvents(CDPSession emitter, string eventName, int eventCount = 1)29 {30 var completion = new TaskCompletionSource<dynamic>();31 void handler(object sender, MessageEventArgs e)32 {33 if (e.MessageID != eventName)34 {35 return;36 }37 --eventCount;38 if (eventCount > 0)39 {40 return;41 }42 emitter.MessageReceived -= handler;43 completion.SetResult(e.MessageData);44 }45 emitter.MessageReceived += handler;...
MessageEventArgs.cs
Source:MessageEventArgs.cs
...5{6 /// <summary>7 /// <seealso cref="CDPSession.MessageReceived"/> arguments.8 /// </summary>9 public class MessageEventArgs10 {11 /// <summary>12 /// Gets or sets the message identifier.13 /// </summary>14 /// <value>The message identifier.</value>15 public string MessageID { get; internal set; }16 /// <summary>17 /// Gets or sets the message data.18 /// </summary>19 /// <value>The message data.</value>20 public JToken MessageData { get; internal set; }21 }22}
MessageEventArgs
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Collections.Generic;4using System.Linq;5using System.Text;6using System.Threading.Tasks;7{8 {9 static void Main(string[] args)10 {11 Console.WriteLine("Hello World!");12 MainAsync().Wait();13 }14 static async Task MainAsync()15 {16 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);17 var browser = await Puppeteer.LaunchAsync(new LaunchOptions18 {19 });20 var page = await browser.NewPageAsync();21 await page.WaitForSelectorAsync("input[title='Search']");22 await page.TypeAsync("input[title='Search']", "PuppeteerSharp");23 await page.WaitForSelectorAsync("input[value='Google Search']");24 await page.ClickAsync("input[value='Google Search']");25 page.RequestCreated += async (sender, e) =>26 {27 Console.WriteLine("Request created: " + e.Request.Url);28 await e.Request.ContinueAsync();29 };30 page.ResponseCreated += async (sender, e) =>31 {32 Console.WriteLine("Response created: " + e.Response.Url);33 await e.Response.ContinueAsync();34 };35 page.ResponseReceived += async (sender, e) =>36 {37 Console.WriteLine("Response received: " + e.Response.Url);38 await e.Response.ContinueAsync();39 };40 page.RequestReceived += async (sender, e) =>41 {42 Console.WriteLine("Request received: " + e.Request.Url);43 await e.Request.ContinueAsync();44 };45 page.Request += async (sender, e) =>46 {47 Console.WriteLine("Request: " + e.Request.Url);48 await e.Request.ContinueAsync();49 };50 page.Response += async (sender, e) =>51 {52 Console.WriteLine("Response: " + e.Response.Url);53 await e.Response.ContinueAsync();54 };55 page.RequestFinished += async (sender, e) =>56 {57 Console.WriteLine("Request finished: " + e.Request.Url);58 await e.Request.ContinueAsync();59 };
MessageEventArgs
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 {9 };10 using (var browser = await Puppeteer.LaunchAsync(options))11 using (var page = await browser.NewPageAsync())12 {13 page.Console += async (sender, e) =>14 {15 Console.WriteLine(e.Message.Text);16 await page.ScreenshotAsync("screenshot.png");17 };18 await page.EvaluateExpressionAsync("console.log('hello')");19 }20 }21 }22}23using PuppeteerSharp;24using System;25using System.Threading.Tasks;26{27 {28 static async Task Main(string[] args)29 {30 {31 };32 using (var browser = await Puppeteer.LaunchAsync(options))33 using (var page = await browser.NewPageAsync())34 {35 page.Console += async (sender, e) =>36 {37 Console.WriteLine(e.Message.Text);38 await page.ScreenshotAsync("screenshot.png");39 };40 await page.EvaluateExpressionAsync("console.log('hello')");41 }42 }43 }44}45using PuppeteerSharp;46using System;47using System.Threading.Tasks;48{49 {50 static async Task Main(string[] args)51 {52 {53 };54 using (var browser = await Puppeteer.LaunchAsync(options))55 using (var page = await browser.NewPageAsync())56 {57 page.Console += async (sender, e) =>58 {59 Console.WriteLine(e.Message.Text);60 await page.ScreenshotAsync("screenshot.png");61 };62 await page.EvaluateExpressionAsync("console.log('hello')");63 }
MessageEventArgs
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4using PuppeteerSharp.Helpers;5{6 {7 public MessageEventArgs(string message)8 {9 Message = message;10 }11 public string Message { get; }12 }13}14using PuppeteerSharp;15using System;16using System.Threading.Tasks;17using PuppeteerSharp.Helpers;18{19 {20 public MessageEventArgs(string message)21 {22 Message = message;23 }24 public string Message { get; }25 }26}27using PuppeteerSharp;28using System;29using System.Threading.Tasks;30using PuppeteerSharp.Helpers;31{32 {33 public MessageEventArgs(string message)34 {35 Message = message;36 }37 public string Message { get; }38 }39}
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!!