如何重新定义ws.send以捕获数据

How to redefine ws.send to capture data?

本文关键字:数据 send 何重新 定义 ws      更新时间:2023-09-26

如何在Chrome中重新定义ws.send以捕获发送的数据?

示例:

ws = new WebSocket('ws://mystuff.com');
ws.send = function(msg) {
    console.log(msg); //should log 'test'
    //Also somehow send the data as it would normally
};
ws.send('test');

您可以将send函数复制到一个新函数,然后覆盖原始函数以添加日志。每次创建websocket实例时,都必须执行此操作。

这就是你可以做到的。

//First, create a clone prototype
Function.prototype.clone = function() {
    var that = this;
    var temp = function temporary() { return that.apply(this, arguments); };
    for(var key in this) {
        if (this.hasOwnProperty(key)) {
            temp[key] = this[key];
        }
    }
    return temp;
};
//Then, when you create your ws object, use the clone function to copy the "send". For example, you can name the new function "parentSend"
ws = new WebSocket('ws://mystuff.com');
ws.parentSend = ws.send.clone();
//Finally, recode a new send function, with the logs, and the call to parentsend()
ws.send = function(msg){
     console.log(msg);
     this.parentSend(msg);
};

这将发送日志,并在之后调用原始函数

我用一种更简单的方法

var ws = new WebSocket("ws://example.com:80");
ws.oldSend = ws.send;
ws.send = function(data) {
    ws.oldSend(data);
    console.log('Captured data:', data);
};`

现在,每当我们调用ws.send时,它都会调用我们重新定义的ws.send,后者会发送它并记录发送的信息。

ws.send('Important data!'); //will show: Captured data: Important data!