From 5e042f603a1485fc54a4f3c4819b69e6a003e26c Mon Sep 17 00:00:00 2001 From: Keith Cirkel Date: Thu, 4 Oct 2018 10:23:21 -0700 Subject: [PATCH] fix: be defensive around use of window.WebSocket --- robust-websocket.js | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/robust-websocket.js b/robust-websocket.js index 8d3bcda..e6969ee 100644 --- a/robust-websocket.js +++ b/robust-websocket.js @@ -11,6 +11,8 @@ } })(function(global, navigator) { + var WebSocket = global.WebSocket + var RobustWebSocket = function(url, protocols, userOptions) { var realWs = { close: function() {} }, connectTimeout, @@ -75,6 +77,12 @@ } self.send = function() { + if (realWs.readyState !== self.OPEN) { + throw Object.assign( + new Error('An attempt was made to use a WebSocket that is not usable'), + { name: 'InvalidStateError' } + ) + } return realWs.send.apply(realWs, arguments) } @@ -93,7 +101,7 @@ } self.open = function() { - if (realWs.readyState !== WebSocket.OPEN && realWs.readyState !== WebSocket.CONNECTING) { + if (realWs.readyState !== self.OPEN && realWs.readyState !== self.CONNECTING) { clearPendingReconnectIfNeeded() reconnectWhenOnlineAgain = false explicitlyClosed = false @@ -239,5 +247,16 @@ } } + ['CONNECTING' , 'OPEN', 'CLOSING', 'CLOSED'].forEach(function (name) { + const descriptor = { + writable: false, + enumerable: true, + configurable: false, + value: WebSocket[name], + } + Object.defineProperty(RobustWebSocket, name, descriptor) + Object.defineProperty(RobustWebSocket.prototype, name, descriptor) + }) + return RobustWebSocket }, typeof window != 'undefined' ? window : (typeof global != 'undefined' ? global : this));