From cd2514630123dd97edf819f9382745c9b97554e1 Mon Sep 17 00:00:00 2001 From: Michael Heuberger Date: Tue, 19 Jan 2016 11:48:00 +1300 Subject: [PATCH] Omit protocols for native WebSockets in browsers only. Fixes TypeErrors, see issue 82. --- stream.js | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/stream.js b/stream.js index 9eb0811..3febd29 100644 --- a/stream.js +++ b/stream.js @@ -6,7 +6,10 @@ module.exports = WebSocketStream function WebSocketStream(target, protocols, options) { var stream, socket - var socketWrite = process.title === 'browser' ? socketWriteBrowser : socketWriteNode + + var isBrowser = process.title === 'browser' + var isNative = !!global.WebSocket + var socketWrite = isBrowser ? socketWriteBrowser : socketWriteNode var proxy = through.obj(socketWrite, socketEnd) if (protocols && !Array.isArray(protocols) && 'object' === typeof protocols) { @@ -19,6 +22,7 @@ function WebSocketStream(target, protocols, options) { // browser only: sets the maximum socket buffer size before throttling var bufferSize = options.browserBufferSize || 1024 * 512 + // browser only: how long to wait when throttling var bufferTimeout = options.browserBufferTimeout || 1000 @@ -27,7 +31,14 @@ function WebSocketStream(target, protocols, options) { socket = target // otherwise make a new one } else { - socket = new WS(target, protocols, options) + // special constructor treatment for native websockets in browsers, see + // https://github.com/maxogden/websocket-stream/issues/82 + if (isNative && isBrowser && !protocols) { + socket = new WS(target) + } else { + socket = new WS(target, protocols, options) + } + socket.binaryType = 'arraybuffer' }