How to override WebSocket send() method

99封情书 提交于 2021-01-01 17:54:02

问题


I'm trying to override the WebSocket.send() method. My objective is being able to fuzz the sent data to test robustness of the server implementation.

I'm adopting this approach:

// OVERRIDE WEBSOCKET SEND METHOD
WebSocket.prototype.oldSend = WebSocket.prototype.send;

WebSocket.prototype.send = function(data) {
     console.log("ws: sending data");
     WebSocket.prototype.oldSend(data);
};

This fails when the WebSocket.prototype.oldSend(data) command is called the first time, with the error: Failed to send: 'send' called on an object that does not implement interface WebSocket.

Anybody if it is possible to override the built-in websocket send method(), or what else I'm missing?

TIA


回答1:


How about:

WebSocket.prototype.oldSend = WebSocket.prototype.send;

WebSocket.prototype.send = function(data) {
     console.log("ws: sending data");
     WebSocket.prototype.oldSend.apply(this, [data]);
};

JSFiddle




回答2:


As far as I know, you can't override WebSocket.send() implementation, as it is read-only in most of browser.

All you can do is something like:

var mysend = function(data) {
    console.log("ws: sending data");
    WebSocket.send(data);
};

which should do the trick anyway, without messing with prototypes.



来源:https://stackoverflow.com/questions/40341197/how-to-override-websocket-send-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!