How to use SendAsync method of PuppeteerSharp.Connection class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Connection.SendAsync

Connection.cs

Source:Connection.cs Github

copy

Full Screen

...71 #region Public Methods72 internal int GetMessageID() => Interlocked.Increment(ref _lastId);73 internal Task RawSendASync(int id, string method, object args, string sessionId = null)74 {75 return Transport.SendAsync(JsonConvert.SerializeObject(76 new ConnectionRequest77 {78 Id = id,79 Method = method,80 Params = args,81 SessionId = sessionId82 },83 JsonHelper.DefaultJsonSerializerSettings));84 }85 internal async Task<JObject> SendAsync(string method, object args = null, bool waitForCallback = true)86 {87 if (IsClosed)88 {89 throw new TargetClosedException($"Protocol error({method}): Target closed.", CloseReason);90 }91 var id = GetMessageID();92 MessageTask callback = null;93 if (waitForCallback)94 {95 callback = new MessageTask96 {97 TaskWrapper = new TaskCompletionSource<JObject>(),98 Method = method99 };100 _callbacks[id] = callback;101 }102 await RawSendASync(id, method, args).ConfigureAwait(false);103 return waitForCallback ? await callback.TaskWrapper.Task.ConfigureAwait(false) : null;104 }105 internal async Task<T> SendAsync<T>(string method, object args = null)106 {107 var response = await SendAsync(method, args).ConfigureAwait(false);108 return response.ToObject<T>(true);109 }110 internal async Task<CDPSession> CreateSessionAsync(TargetInfo targetInfo)111 {112 var sessionId = (await SendAsync<TargetAttachToTargetResponse>("Target.attachToTarget", new TargetAttachToTargetRequest113 {114 TargetId = targetInfo.TargetId,115 Flatten = true116 }).ConfigureAwait(false)).SessionId;117 return await GetSessionAsync(sessionId).ConfigureAwait(false);118 }119 internal bool HasPendingCallbacks() => _callbacks.Count != 0;120 #endregion121 internal void Close(string closeReason)122 {123 if (IsClosed)124 {125 return;126 }...

Full Screen

Full Screen

CDPSession.cs

Source:CDPSession.cs Github

copy

Full Screen

...8namespace PuppeteerSharp9{10 /// <summary>11 /// The CDPSession instances are used to talk raw Chrome Devtools Protocol:12 /// * Protocol methods can be called with <see cref="CDPSession.SendAsync(string, object, bool)"/> method.13 /// * Protocol events, using the <see cref="CDPSession.MessageReceived"/> event.14 ///15 /// Documentation on DevTools Protocol can be found here: <see href="https://chromedevtools.github.io/devtools-protocol/"/>.16 ///17 /// <code>18 /// <![CDATA[19 /// var client = await Page.Target.CreateCDPSessionAsync();20 /// await client.SendAsync("Animation.enable");21 /// client.MessageReceived += (sender, e) =>22 /// {23 /// if (e.MessageID == "Animation.animationCreated")24 /// {25 /// Console.WriteLine("Animation created!");26 /// }27 /// };28 /// JObject response = await client.SendAsync("Animation.getPlaybackRate");29 /// Console.WriteLine("playback rate is " + response.playbackRate);30 /// await client.SendAsync("Animation.setPlaybackRate", new31 /// {32 /// playbackRate = Convert.ToInt32(response.playbackRate / 2)33 /// });34 /// ]]></code>35 /// </summary>36 public class CDPSession37 {38 internal CDPSession(Connection connection, TargetType targetType, string sessionId)39 {40 Connection = connection;41 TargetType = targetType;42 SessionId = sessionId;43 _callbacks = new ConcurrentDictionary<int, MessageTask>();44 }45 #region Private Members46 private readonly ConcurrentDictionary<int, MessageTask> _callbacks;47 #endregion48 #region Properties49 /// <summary>50 /// Gets the target type.51 /// </summary>52 /// <value>The target type.</value>53 public TargetType TargetType { get; }54 /// <summary>55 /// Gets the session identifier.56 /// </summary>57 /// <value>The session identifier.</value>58 public string SessionId { get; }59 /// <summary>60 /// Gets the connection.61 /// </summary>62 /// <value>The connection.</value>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 {...

Full Screen

Full Screen

CSSCoverage.cs

Source:CSSCoverage.cs Github

copy

Full Screen

...34 _stylesheetURLs.Clear();35 _stylesheetSources.Clear();36 _client.MessageReceived += client_MessageReceived;37 return Task.WhenAll(38 _client.SendAsync("DOM.enable"),39 _client.SendAsync("CSS.enable"),40 _client.SendAsync("CSS.startRuleUsageTracking")41 );42 }43 internal async Task<CoverageEntry[]> StopAsync()44 {45 if (!_enabled)46 {47 throw new InvalidOperationException("CSSCoverage is not enabled");48 }49 _enabled = false;50 var ruleTrackingResponseTask = _client.SendAsync<CSSStopRuleUsageTrackingResponse>("CSS.stopRuleUsageTracking");51 await Task.WhenAll(52 ruleTrackingResponseTask,53 _client.SendAsync("CSS.disable"),54 _client.SendAsync("DOM.disable")55 ).ConfigureAwait(false);56 _client.MessageReceived -= client_MessageReceived;57 var styleSheetIdToCoverage = new Dictionary<string, List<CoverageResponseRange>>();58 foreach (var entry in ruleTrackingResponseTask.Result.RuleUsage)59 {60 styleSheetIdToCoverage.TryGetValue(entry.StyleSheetId, out var ranges);61 if (ranges == null)62 {63 ranges = new List<CoverageResponseRange>();64 styleSheetIdToCoverage[entry.StyleSheetId] = ranges;65 }66 ranges.Add(new CoverageResponseRange67 {68 StartOffset = entry.StartOffset,69 EndOffset = entry.EndOffset,70 Count = entry.Used ? 1 : 0,71 });72 }73 var coverage = new List<CoverageEntry>();74 foreach (var styleSheetId in _stylesheetURLs.Keys)75 {76 var url = _stylesheetURLs[styleSheetId];77 var text = _stylesheetSources[styleSheetId];78 styleSheetIdToCoverage.TryGetValue(styleSheetId, out var responseRanges);79 var ranges = Coverage.ConvertToDisjointRanges(responseRanges ?? new List<CoverageResponseRange>());80 coverage.Add(new CoverageEntry81 {82 Url = url,83 Ranges = ranges,84 Text = text85 });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))104 {105 return;106 }107 try108 {109 var response = await _client.SendAsync("CSS.getStyleSheetText", new110 {111 styleSheetId = styleSheetAddedResponse.Header.StyleSheetId112 }).ConfigureAwait(false);113 _stylesheetURLs.Add(styleSheetAddedResponse.Header.StyleSheetId, styleSheetAddedResponse.Header.SourceURL);114 _stylesheetSources.Add(styleSheetAddedResponse.Header.StyleSheetId, response[MessageKeys.Text].AsString());115 }116 catch (Exception ex)117 {118 _logger.LogError(ex.ToString());119 }120 }121 private void OnExecutionContextsCleared()122 {123 if (!_resetOnNavigation)...

Full Screen

Full Screen

JSCoverage.cs

Source:JSCoverage.cs Github

copy

Full Screen

...37 _scriptURLs.Clear();38 _scriptSources.Clear();39 _client.MessageReceived += client_MessageReceived;40 return Task.WhenAll(41 _client.SendAsync("Profiler.enable"),42 _client.SendAsync("Profiler.startPreciseCoverage", new { callCount = false, detailed = true }),43 _client.SendAsync("Debugger.enable"),44 _client.SendAsync("Debugger.setSkipAllPauses", new { skip = true })45 );46 }47 internal async Task<CoverageEntry[]> StopAsync()48 {49 if (!_enabled)50 {51 throw new InvalidOperationException("JSCoverage is not enabled");52 }53 _enabled = false;54 var profileResponseTask = _client.SendAsync<ProfilerTakePreciseCoverageResponse>("Profiler.takePreciseCoverage");55 await Task.WhenAll(56 profileResponseTask,57 _client.SendAsync("Profiler.stopPreciseCoverage"),58 _client.SendAsync("Profiler.disable"),59 _client.SendAsync("Debugger.disable")60 ).ConfigureAwait(false);61 _client.MessageReceived -= client_MessageReceived;62 var coverage = new List<CoverageEntry>();63 foreach (var entry in profileResponseTask.Result.Result)64 {65 _scriptURLs.TryGetValue(entry.ScriptId, out var url);66 if (string.IsNullOrEmpty(url) && _reportAnonymousScripts)67 {68 url = "debugger://VM" + entry.ScriptId;69 }70 if (string.IsNullOrEmpty(url) ||71 !_scriptSources.TryGetValue(entry.ScriptId, out var text))72 {73 continue;74 }75 var flattenRanges = entry.Functions.SelectMany(f => f.Ranges).ToList();76 var ranges = Coverage.ConvertToDisjointRanges(flattenRanges);77 coverage.Add(new CoverageEntry78 {79 Url = url,80 Ranges = ranges,81 Text = text82 });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 ||101 (string.IsNullOrEmpty(scriptParseResponse.Url) && !_reportAnonymousScripts))102 {103 return;104 }105 try106 {107 var response = await _client.SendAsync("Debugger.getScriptSource", new { scriptId = scriptParseResponse.ScriptId }).ConfigureAwait(false);108 _scriptURLs.Add(scriptParseResponse.ScriptId, scriptParseResponse.Url);109 _scriptSources.Add(scriptParseResponse.ScriptId, response[MessageKeys.ScriptSource].AsString());110 }111 catch (Exception ex)112 {113 _logger.LogError(ex.ToString());114 }115 }116 private void OnExecutionContextsCleared()117 {118 if (!_resetOnNavigation)119 {120 return;121 }...

Full Screen

Full Screen

CreateCDPSessionTests.cs

Source:CreateCDPSessionTests.cs Github

copy

Full Screen

...20 public async Task ShouldWork()21 {22 var client = await Page.Target.CreateCDPSessionAsync();23 await Task.WhenAll(24 client.SendAsync("Runtime.enable"),25 client.SendAsync("Runtime.evaluate", new RuntimeEvaluateRequest { Expression = "window.foo = 'bar'" })26 );27 var foo = await Page.EvaluateExpressionAsync<string>("window.foo");28 Assert.Equal("bar", foo);29 }30 [PuppeteerTest("CDPSession.spec.ts", "Target.createCDPSession", "should send events")]31 [SkipBrowserFact(skipFirefox: true)]32 public async Task ShouldSendEvents()33 {34 var client = await Page.Target.CreateCDPSessionAsync();35 await client.SendAsync("Network.enable");36 var events = new List<object>();37 client.MessageReceived += (_, e) =>38 {39 if (e.MessageID == "Network.requestWillBeSent")40 {41 events.Add(e.MessageData);42 }43 };44 await Page.GoToAsync(TestConstants.EmptyPage);45 Assert.Single(events);46 }47 [PuppeteerTest("CDPSession.spec.ts", "Target.createCDPSession", "should enable and disable domains independently")]48 [SkipBrowserFact(skipFirefox: true)]49 public async Task ShouldEnableAndDisableDomainsIndependently()50 {51 var client = await Page.Target.CreateCDPSessionAsync();52 await client.SendAsync("Runtime.enable");53 await client.SendAsync("Debugger.enable");54 // JS coverage enables and then disables Debugger domain.55 await Page.Coverage.StartJSCoverageAsync();56 await Page.Coverage.StopJSCoverageAsync();57 // generate a script in page and wait for the event.58 var eventTask = WaitEvent(client, "Debugger.scriptParsed");59 await Task.WhenAll(60 eventTask,61 Page.EvaluateExpressionAsync("//# sourceURL=foo.js")62 );63 // expect events to be dispatched.64 Assert.Equal("foo.js", eventTask.Result["url"].Value<string>());65 }66 [PuppeteerTest("CDPSession.spec.ts", "Target.createCDPSession", "should be able to detach session")]67 [SkipBrowserFact(skipFirefox: true)]68 public async Task ShouldBeAbleToDetachSession()69 {70 var client = await Page.Target.CreateCDPSessionAsync();71 await client.SendAsync("Runtime.enable");72 var evalResponse = await client.SendAsync("Runtime.evaluate", new RuntimeEvaluateRequest73 {74 Expression = "1 + 2",75 ReturnByValue = true76 });77 Assert.Equal(3, evalResponse["result"]["value"].ToObject<int>());78 await client.DetachAsync();79 var exception = await Assert.ThrowsAnyAsync<Exception>(()80 => client.SendAsync("Runtime.evaluate", new RuntimeEvaluateRequest81 {82 Expression = "3 + 1",83 ReturnByValue = true84 }));85 Assert.Contains("Session closed.", exception.Message);86 }87 [PuppeteerTest("CDPSession.spec.ts", "Target.createCDPSession", "should throw nice errors")]88 [SkipBrowserFact(skipFirefox: true)]89 public async Task ShouldThrowNiceErrors()90 {91 var client = await Page.Target.CreateCDPSessionAsync();92 async Task TheSourceOfTheProblems() => await client.SendAsync("ThisCommand.DoesNotExist");93 var exception = await Assert.ThrowsAsync<MessageException>(async () =>94 {95 await TheSourceOfTheProblems();96 });97 Assert.Contains("TheSourceOfTheProblems", exception.StackTrace);98 Assert.Contains("ThisCommand.DoesNotExist", exception.Message);99 }100 [PuppeteerTest("CDPSession.spec.ts", "Target.createCDPSession", "should expose the underlying connection")]101 [SkipBrowserFact(skipFirefox: true)]102 public async Task ShouldExposeTheUnderlyingConnection()103 => Assert.NotNull(await Page.Target.CreateCDPSessionAsync());104 }105}...

Full Screen

Full Screen

IConnection.cs

Source:IConnection.cs Github

copy

Full Screen

...28 /// <param name="waitForCallback">29 /// If <c>true</c> the method will return a task to be completed when the message is confirmed by Chromium.30 /// If <c>false</c> the task will be considered complete after sending the message to Chromium.31 /// </param>32 Task<JObject> SendAsync(string method, dynamic args = null, bool waitForCallback = true);33 /// <summary>34 /// Gets the parent connection35 /// </summary>36 IConnection Connection { get; }37 /// <summary>38 /// Occurs when the connection is closed.39 /// </summary>40 event EventHandler Closed;41 }42}...

Full Screen

Full Screen

MessageException.cs

Source:MessageException.cs Github

copy

Full Screen

...3using PuppeteerSharp.Messaging;4namespace PuppeteerSharp5{6 /// <summary>7 /// Exception thrown by <seealso cref="CDPSession.SendAsync(string, object)"/>8 /// </summary>9 public class MessageException : PuppeteerException10 {11 /// <summary>12 /// Initializes a new instance of the <see cref="MessageException"/> class.13 /// </summary>14 /// <param name="message">Message.</param>15 public MessageException(string message) : base(message)16 {17 }18 /// <summary>19 /// Initializes a new instance of the <see cref="MessageException"/> class.20 /// </summary>21 /// <param name="message">Message.</param>...

Full Screen

Full Screen

IConnectionTransport.cs

Source:IConnectionTransport.cs Github

copy

Full Screen

...19 /// Sends a message using the transport.20 /// </summary>21 /// <returns>The task.</returns>22 /// <param name="message">Message to send.</param>23 Task SendAsync(string message);24 /// <summary>25 /// Occurs when the transport is closed.26 /// </summary>27 event EventHandler<TransportClosedEventArgs> Closed;28 /// <summary>29 /// Occurs when a message is received.30 /// </summary>31 event EventHandler<MessageReceivedEventArgs> MessageReceived;32 }33}...

Full Screen

Full Screen

SendAsync

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {

Full Screen

Full Screen

SendAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4using PuppeteerSharp.Messaging;5{6 {7 static async Task Main(string[] args)8 {

Full Screen

Full Screen

SendAsync

Using AI Code Generation

copy

Full Screen

1var response = await connection.SendAsync("Page.navigate", new Dictionary<string, object>2{3});4Console.WriteLine("Response: " + response);5using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))6{7 var page = await browser.NewPageAsync();8 Console.WriteLine(response);9}10using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))11{12 var response = await browser.SendAsync("Page.navigate", new Dictionary<string, object>13 {14 });15 Console.WriteLine(response);16}

Full Screen

Full Screen

SendAsync

Using AI Code Generation

copy

Full Screen

1var connection = new Connection(url);2var message = new Dictionary<string, object>();3message.Add("method", "Page.navigate");4var parameters = new Dictionary<string, object>();5message.Add("params", parameters);6await connection.SendAsync(message);7 at PuppeteerSharp.Connection.SendAsync (System.Collections.Generic.Dictionary`2[TKey,TValue] message) [0x00000] in <filename unknown>:0 8 at PuppeteerSharp.Connection.SendAsync[T] (System.Collections.Generic.Dictionary`2[TKey,TValue] message) [0x00000] in <filename unknown>:0 9 at PuppeteerSharp.Page.GoToAsync (System.String url, System.Boolean waitUntil, System.String[] waitUntilOptions) [0x00000] in <filename unknown>:0 10 at PuppeteerSharp.Page.GoToAsync (System.String url, System.Boolean waitUntil) [0x00000] in <filename unknown>:0 11 at PuppeteerSharp.Page.GoToAsync (System.String url) [0x00000] in <filename unknown>:0 12 at PuppeteerSharp.Page.GoToAsync (System.String url, PuppeteerSharp.WaitUntilNavigation waitUntil) [0x00000] in <filename unknown>:0 13 at PuppeteerSharp.Page.GoToAsync (System.String url, PuppeteerSharp.WaitUntilNavigation waitUntil, System.Int32 timeout) [0x00000] in <filename unknown>:0 14 at PuppeteerSharp.Page.GoToAsync (System.String url, PuppeteerSharp.WaitUntilNavigation waitUntil, System.Int32 timeout, System.Boolean throwOnTimeout) [0x00000] in <filename unknown>:0 15 at PuppeteerSharp.Page.GoToAsync (System.String url, PuppeteerSharp.WaitUntilNavigation waitUntil, System.Int32 timeout, System.Boolean throwOnTimeout, System.Boolean ignoreHTTPSErrors) [0x00000] in <filename unknown>:0 16 at PuppeteerSharp.Page.GoToAsync (System.String url, PuppeteerSharp.WaitUntilNavigation waitUntil, System.Int32 timeout, System.Boolean throwOnTimeout, System.Boolean ignoreHTTPSErrors, System.Boolean bypassCSP) [0x00000] in <filename unknown>:

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