从“网络”选项卡捕获Websocket消息

时间:2019-09-11 16:33:25

标签: chromium puppeteer

我使用伪音符尝试读取websocket消息并将其放入字符串中以输出到控制台。要查看一些网络套接字消息的示例,您可以访问下面代码中提供的链接,然后按照括号中的步骤进行操作。 (CTRL + SHIFT + I>网络> WS(websocket)>消息)

var puppeteer = require('puppeteer');

async function run() {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.goto('http://powerline.io');
    console.log('navigated successfully');
    page.on('response', response => {
        const isWSS = ['websocket'].includes(response.request().resourceType())

        if (isWSS){
            console.log(isWSS);
            log(response.url());
            response.text().then(log)
        }
    })
}

run();

1 个答案:

答案 0 :(得分:2)

下面是一个示例,说明如何捕获它:

var puppeteer = require('puppeteer');

async function run() {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  await page.goto('http://powerline.io');
  const cdp = await page.target().createCDPSession();
  await cdp.send('Network.enable');
  await cdp.send('Page.enable');

  const printResponse = response => console.log('response: ', response);

  cdp.on('Network.webSocketFrameReceived', printResponse); // Fired when WebSocket message is received.
  cdp.on('Network.webSocketFrameSent', printResponse); // Fired when WebSocket message is sent.
}

run();

详细了解network events