Skip to content

Commit

Permalink
[fix] Fix Websocket implementation in React Native (#607)
Browse files Browse the repository at this point in the history
As `self` is undefined in React Native.
  • Loading branch information
bensalilijames authored and darrachequesne committed Jan 20, 2019
1 parent 696c7e7 commit 1ec53d4
Showing 1 changed file with 16 additions and 7 deletions.
23 changes: 16 additions & 7 deletions lib/transports/websocket.js
Expand Up @@ -8,13 +8,17 @@ var parseqs = require('parseqs');
var inherit = require('component-inherit');
var yeast = require('yeast');
var debug = require('debug')('engine.io-client:websocket');

var BrowserWebSocket, NodeWebSocket;
if (typeof self === 'undefined') {

if (typeof WebSocket !== 'undefined') {
BrowserWebSocket = WebSocket;
} else if (typeof self !== 'undefined') {
BrowserWebSocket = self.WebSocket || self.MozWebSocket;
} else {
try {
NodeWebSocket = require('ws');
} catch (e) { }
} else {
BrowserWebSocket = self.WebSocket || self.MozWebSocket;
}

/**
Expand All @@ -23,7 +27,7 @@ if (typeof self === 'undefined') {
* interface exposed by `ws` for Node-like environment.
*/

var WebSocket = BrowserWebSocket || NodeWebSocket;
var WebSocketImpl = BrowserWebSocket || NodeWebSocket;

/**
* Module exports.
Expand All @@ -47,7 +51,7 @@ function WS (opts) {
this.usingBrowserWebSocket = BrowserWebSocket && !opts.forceNode;
this.protocols = opts.protocols;
if (!this.usingBrowserWebSocket) {
WebSocket = NodeWebSocket;
WebSocketImpl = NodeWebSocket;
}
Transport.call(this, opts);
}
Expand Down Expand Up @@ -107,7 +111,12 @@ WS.prototype.doOpen = function () {
}

try {
this.ws = this.usingBrowserWebSocket && !this.isReactNative ? (protocols ? new WebSocket(uri, protocols) : new WebSocket(uri)) : new WebSocket(uri, protocols, opts);
this.ws =
this.usingBrowserWebSocket && !this.isReactNative
? protocols
? new WebSocketImpl(uri, protocols)
: new WebSocketImpl(uri)
: new WebSocketImpl(uri, protocols, opts);
} catch (err) {
return this.emit('error', err);
}
Expand Down Expand Up @@ -280,5 +289,5 @@ WS.prototype.uri = function () {
*/

WS.prototype.check = function () {
return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
return !!WebSocketImpl && !('__initialize' in WebSocketImpl && this.name === WS.prototype.name);
};

0 comments on commit 1ec53d4

Please sign in to comment.