我如何重新定义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');
答案 0 :(得分:0)
您可以将发送功能复制到新功能,然后覆盖原始功能以添加日志。 每次创建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);
};
这将发送日志,并在
之后调用原始函数答案 1 :(得分:0)
我做得更简单
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!