问题
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