Reputation: 179
I use puppeteer-sharp to dump data received and send by page via websockets. The code to dump data in C#:
async Task Dump()
{
var client = await _browser.Page.Target.CreateCDPSessionAsync();
await client.SendAsync("Network.enable");
client.MessageReceived += OnChromeDevProtocolMessage;
}
void OnChromeDevProtocolMessage(object sender, MessageEventArgs eventArgs)
{
if (eventArgs.MessageID == "Network.webSocketCreated")
{
Logger.Trace($"Network.webSocketCreated: {eventArgs.MessageData}");
}
else if (eventArgs.MessageID == "Network.webSocketFrameSent")
{
Logger.Trace($"Network.webSocketFrameSent: {eventArgs.MessageData}");
}
else if (eventArgs.MessageID == "Network.webSocketFrameReceived")
{
var cdpMessage = JsonConvert.DeserializeObject<CdpMessage>(eventArgs.MessageData.ToString());
ProcessMessage(cdpMessage);
}
}
Is there any way to send data to websockets using puppeteer or using directly Chrome Dev Protocol messages?
EDIT: Or is it possible to get somehow WebSocket instanse (or handle) to use it in JavaScript code to send data using EvaluateFunctionAsync?
Upvotes: 4
Views: 3860
Reputation: 6079
in case someone comes to this question looking for an answer in javascript:
const prototype = await page.evaluateHandle("WebSocket.prototype");
const socketInstances = await page.queryObjects(prototype);
await page.evaluate((instances) => {
let instance = instances[0];
instance.send('Hello');
}, socketInstances);
and for ViniCoder in the comments, pyppeteer in python:
prototype = await page.evaluateHandle("WebSocket.prototype")
socketInstances = await page.queryObjects(prototype)
await page.evaluate('''(instances) => {
let instance = instances[0];
instance.send('Hello');
}''', socketInstances)
Upvotes: 2
Reputation: 101
QueryObjects can be used in the command line API and also in Puppeteer in order to find the instance. After that you just use EvaluateFunction, to execute send method on object. In PuppeteerSharp it looks something like this:
//CODE SNIPPET
var prototype = await page.EvaluateExpressionHandleAsync("WebSocket.prototype");
var socketInstances = await page.QueryObjectsAsync(prototype);
await page.EvaluateFunctionAsync("(instances) => {let instance = instances[0]; instance.send('Hello')}, new[] {socketInstances}");
More information can be found in the documentation.
Upvotes: 6