问题
I have spent a couple weeks on this issue and I can’t seem to find a resolution. Here is the use case. I am developing a chrome extension, one of the main purposes of this extension is to detect when a WebSocket opens or closes. I have looked at the HTML5 spec for WebSockets, they expose the following related methods/events:
WebSocket.prototype.readyState = 0;
WebSocket.prototype.onopen = 0;
WebSocket.prototype.onerror = 0;
WebSocket.prototype.onclose = 0;
function WebSocket(url,protocols) {}
WebSocket.prototype.close = function(code,reason) {};
Since I don’t have access to the individual instance from within the extension, I have to rely on wrapping these prototypes to find out when they are called. For example:
WebSocket.prototype.close = function (close) {
console.log("Closing socket....");
return function (code, reason) {
return close.apply(this, arguments);
};
}(WebSocket.prototype.close);
However, what I really want to do is somehow wrap or register listeners for onopen, onerror, or onclose. Unfortunately I do not know how to do this. I tried a bunch of different approaches. The approach above works for 'close', but they do not offer 'open', which I am dependent on. The most promising idea, which did not work, was the following:
WebSocket.prototype.constructor = function (constructor) {
debugger;
console.log("Register all my events here!");
constructor.apply(this, arguments);
}(WebSocket.prototype.constructor);
Unfortunately, I was never able to hit a breakpoint, or see console logs, which led me to believe I was doing something wrong.
As a last resort, I tried to play around with Object.Observe(), but was unable to observe the prototype:
Object.observe(WebSocket.prototype.readyState, function (changes) {
console.log("Ready state");
});
Object.observe(WebSocket.prototype.onopen, function (changes) {
console.log("On open");
});
So, to sum things up, I have tried a few different approaches, but ultimately I have hit a wall. In the end my goal is to detect when a WebSocket opens or closes by listening to any of the exposed methods or events. Any help would be greatly appreciated.
Update: Here is a fiddle, including the suggestions below:
http://jsfiddle.net/s35zpfq9/1/
Thanks!
回答1:
you can wrap the WebSocket to spy on all instances created after you switch it:
(function(){
var ws = window.WebSocket;
window.WebSocket = function (a, b) {
var that = b ? new ws(a, b) : new ws(a);
that.addEventListener("open", console.info.bind(console, "socket open"));
that.addEventListener("close", console.info.bind(console, "socket close"));
that.addEventListener("message", console.info.bind(console, "socket msg"));
return that;
};
window.WebSocket.prototype=ws.prototype;
}());
来源:https://stackoverflow.com/questions/33712810/listening-to-a-websocket-connection-through-prototypes