如何使用Puppeteer将数据发送到WebSocket

jdgnovmf  于 2022-11-11  发布在  其他
关注(0)|答案(2)|浏览(279)

我使用puppeteer-sharp通过websockets转储页面接收和发送的数据。

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);
    }
}

有没有办法使用puppeteer或直接使用Chrome开发协议消息将数据发送到websockets?

**EDIT:**或者,是否可以通过某种方式获得WebSocket示例(或句柄),以便在JavaScript代码中使用它来使用EvaluateFunctionAsync发送数据?

dwbf0jvd

dwbf0jvd1#

QueryObjects可以在命令行API中使用,也可以在Puppeteer中使用,以便查找示例。之后,您只需使用EvaluateFunction,对对象执行send方法。在PuppeteerSharp中,它看起来如下所示:

//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}");

有关详细信息,请参阅文档。

5tmbdcev

5tmbdcev2#

如果有人在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);

评论中的ViniCoder,Python中的pyppeteer:

prototype       = await page.evaluateHandle("WebSocket.prototype")
socketInstances = await page.queryObjects(prototype)
await page.evaluate('''(instances) => {
  let instance = instances[0];
  instance.send('Hello');
}''', socketInstances)

相关问题