How to control a websocket with Chrome DevTools?

Viewed 158

I'm currently working on capturing crypto-currency price infos from OKEX. I found that, when a page navigate to https://www.okex.com/trade-spot/eth-usdt, it will initiate a websocket named public and send subscription orders via this websocket. Then, data corresponding sent subscriptions will flow through the same websocket.

My question is, in addition to passively inspecting dataflows in this websocket, is there any way to control it, namely to send subscriptions? If so, can this approch be automated(by puppeteer or something equivalent)?

1 Answers

After some research and learning, I solved this problem using evaluateHandle() and queryObjects(). However communication via selected websockets must be done in DOM context.

const puppeteer = require('puppeteer');

async function unsubscrible(page, wsHandle){
    page.evaluate(arr=>{
        arr[0].send(JSON.stringify({"op": "unsubscribe","args":[{"channel":"instruments","instType":"SPOT"},{"channel":"instruments","instType":"FUTURES"},{"channel":"instruments","instType":"SWAP"},{"channel":"instruments","instType":"OPTION"},{"channel":"tickers","instId":"ETH-USDT"},{"channel":"cup-tickers-3s","ccy":"USDT"},{"channel":"mark-price","instId":"ETH-USDT"},{"channel":"index-tickers","instId":"ETH-USDT"},{"channel":"itn-status"},{"channel":"optimized-books","instId":"ETH-USDT"},{"channel":"trades","instId":"ETH-USDT"}]}));
    }, wsHandle);
};

async function ping(page, wsHandle){
    page.evaluate(arr=>{
        arr[0].send('ping');
    }, wsHandle);
}


async function main() {  
    const browser = await puppeteer.launch({
        headless : false,
        args : [
            '--auto-open-devtools-for-tabs',
        ]
    });

    const page = (await browser.pages())[0];
    page.setDefaultNavigationTimeout(0);  
    await page.goto('https://www.okex.com/trade-spot/eth-usdt');

    const wsHandle = await page.evaluateHandle(()=>WebSocket.prototype);
    
    const ws = await page.queryObjects(wsHandle);
      
    await unsubscrible(page, ws);

    setTimeout(()=>{
        for (i=0; i<10; i++) ping(page, ws);
    }, 20000)
    
}


main();
Related