Skip to content

Commit

Permalink
fix(react-native): restrict the list of options for the WebSocket object
Browse files Browse the repository at this point in the history
Only 'headers' and 'localAddress' options are supported by the
WebSocket implementation in React Native.

The following message was printed to the console:

> Unrecognized WebSocket connection option(s) `agent`, `perMessageDeflate`, `pfx`, `key`, `passphrase`, `cert`, `ca`, `ciphers`, `rejectUnauthorized`. Did you mean to put these under `headers`?

Reference: https://reactnative.dev/docs/network.html#websocket-support
  • Loading branch information
darrachequesne committed May 25, 2020
1 parent 86d4e8d commit 2f5c948
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 20 deletions.
6 changes: 0 additions & 6 deletions lib/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,6 @@ class Socket extends Emitter {
this.opts.query = parseqs.decode(this.opts.query);
}

// detect ReactNative environment
this.opts.isReactNative =
typeof navigator !== "undefined" &&
typeof navigator.product === "string" &&
navigator.product.toLowerCase() === "reactnative";

// set on handshake
this.id = null;
this.upgrades = null;
Expand Down
41 changes: 27 additions & 14 deletions lib/transports/websocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ const { WebSocket, usingBrowserWebSocket } = require("./websocket-constructor");

const debug = require("debug")("engine.io-client:websocket");

// detect ReactNative environment
const isReactNative =
typeof navigator !== "undefined" &&
typeof navigator.product === "string" &&
navigator.product.toLowerCase() === "reactnative";

class WS extends Transport {
/**
* WebSocket transport constructor.
Expand Down Expand Up @@ -47,26 +53,33 @@ class WS extends Transport {

const uri = this.uri();
const protocols = this.opts.protocols;
const opts = pick(
this.opts,
"agent",
"perMessageDeflate",
"pfx",
"key",
"passphrase",
"cert",
"ca",
"ciphers",
"rejectUnauthorized",
"localAddress"
);

let opts;
if (isReactNative) {
opts = pick(this.opts, "localAddress");
} else {
opts = pick(
this.opts,
"agent",
"perMessageDeflate",
"pfx",
"key",
"passphrase",
"cert",
"ca",
"ciphers",
"rejectUnauthorized",
"localAddress"
);
}

if (this.opts.extraHeaders) {
opts.headers = this.opts.extraHeaders;
}

try {
this.ws =
usingBrowserWebSocket && !this.opts.isReactNative
usingBrowserWebSocket && !isReactNative
? protocols
? new WebSocket(uri, protocols)
: new WebSocket(uri)
Expand Down

0 comments on commit 2f5c948

Please sign in to comment.