Package Exports
- jetsocket-js
- jetsocket-js/dist/node/jetsocket.js
- jetsocket-js/dist/react-native/jetsocket.js
- jetsocket-js/dist/web/jetsocket.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (jetsocket-js) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Jetsocket Javascript Client
This Jetsocket client library supports web browsers, web workers and Node.js
If you're looking for the Jetsocket server library for Node.js, use jetsocket-node instead.
Usage Overview
The following topics are covered:
- Installation
- Initialization
- Configuration
- Global Configuration
- Connection
- Subscribing to Channels (Public and Private)
- Accessing Channels
- Binding to Events
- Default events
- Developing
Supported platforms
Web
We test against Chrome, Firefox and Safari.
Works with all major web frameworks, including
- Angular
- React
- Vue.js
Installation
Web
If you're using Jetsocket on a web page, you can install the library via:
Encrypted Channel Support
The encryption primitives required to power encrypted channels increase the bundle size quite significantly. In order to keep bundle sizes down, the default web and worker builds of jetsocket-js no longer support encrypted channels.
If you'd like to make use of encrypted-channels, you need to import the
with-encryption
builds as described below.
Yarn (or NPM)
You can use any NPM-compatible package manager, including NPM itself and Yarn.
yarn add jetsocket-js
Then:
import Jetsocket from 'jetsocket-js';
If you'd like to use encrypted channels:
import Jetsocket from 'jetsocket-js/with-encryption';
Or, if you're not using ES6 modules:
const Jetsocket = require('jetsocket-js');
If you'd like to use encrypted channels:
const Jetsocket = require('jetsocket-js/with-encryption');
CDN
<script src="https://js.jetsocket.io/latest/jetsocket.min.js"></script>
If you'd like to use encrypted channels:
<script src="https://js.jetsocket.io/latest/jetsocket-with-encryption.min.js"></script>
Bower (discouraged)
Or via Bower:
bower install jetsocket
and then:
<script src="bower_components/jetsocket/dist/web/jetsocket.min.js"></script>
Typescript
We've provided typescript declarations since v5.1.0. Most things should work out of the box but if you need access to specific types you can import them like so:
import Jetsocket from 'jetsocket-js';
import * as JetsocketTypes from 'jetsocket-js';
var presenceChannel: JetsocketTypes.PresenceChannel;
...
React Native
⚠️ Important notice
React Native support has been deprecated and soon will be removed from this repository.
Please, use our official React Native SDK instead.
Web Workers
(jetsocket-js
's Web Workers implementation is currently not compatible with Internet Explorer)
You can import the worker script (jetsocket.worker.js
, not jetsocket.js
) from the CDN:
importScripts('https://js.jetsocket.io/latest/jetsocket.worker.min.js');
If you'd like to use encrypted channels:
importScripts('https://js.jetsocket.io/latest/jetsocket-with-encryption.worker.min.js');
If you're building your worker with a bundler, you can import the worker entrypoint
import Jetsocket from 'jetsocket-js/worker'
If you'd like to use encrypted channels:
import Jetsocket from 'jetsocket-js/worker/with-encryption'
Node.js
Having installed jetsocket-js
via an NPM-compatible package manager, run:
import Jetsocket from 'jetsocket-js';
Initialization
const jetsocket = new Jetsocket(APP_KEY, {
cluster: APP_CLUSTER,
});
You can get your APP_KEY
and APP_CLUSTER
from the Jetsocket Webapp.
Configuration
There are a number of configuration parameters which can be set for the client, which can be passed as an object to the Jetsocket constructor, i.e.:
const jetsocket = new Jetsocket(APP_KEY, {
cluster: APP_CLUSTER,
channelAuthorization: {
endpoint: 'http://example.com/jetsocket/auth'
},
});
For most users, there is little need to change these.
forceTLS
(Boolean)
Forces the connection to use TLS. When set to false
the library will attempt non-TLS connections first. Defaults to true
.
userAuthentication
(Object)
Object containing the configuration for user authentication. Valid keys are:
endpoint
(String) - Endpoint on your server that will return the authentication signature needed for signing the user in. Defaults to/jetsocket/user-auth
.transport
(String) - Defines how the authentication endpoint will be called. There are two options available:ajax
- the default option where anXMLHttpRequest
object will be used to make a request. The parameters will be passed asPOST
parameters.jsonp
- The authentication endpoint will be called by a<script>
tag being dynamically created pointing to the endpoint defined byuserAuthentication.endpoint
. This can be used when the authentication endpoint is on a different domain to the web application. The endpoint will therefore be requested as aGET
and parameters passed in the query string.
params
(Object) - Additional parameters to be sent when the user authentication endpoint is called. When using ajax authentication the parameters are passed as additional POST parameters. When using jsonp authentication the parameters are passed as GET parameters. This can be useful with web application frameworks that guard against CSRF (Cross-site request forgery).headers
(Object) - Only applied when usingajax
as authentication transport. Provides the ability to pass additional HTTP Headers to the user authentication endpoint. This can be useful with some web application frameworks that guard against CSRF CSRF (Cross-site request forgery).paramsProvider
(Function) - When present, this function is called to get additional parameters to be sent when the user authentication endpoint is called. This is equivalent to passing them on the params key, but allows for the parameters to be retrieved dynamically at the time of the request.headersProvider
(Function) - When present, this function is called to get additional headers to be sent when the user authentication endpoint is called. This is equivalent to passing them on the headers key, but allows for the headers to be retrieved dynamically at the time of the request.customHandler
(Function) - When present, this function is called instead of a request being made to the endpoint specified byuserAuthentication.endpoint
.
channelAuthorization
(Object)
Object containing the configuration for user authorization. Valid keys are:
endpoint
(String) - Endpoint on your server that will return the authorization signature needed for private and presence channels. Defaults to/jetsocket/auth
.transport
(String) - Defines how the authorization endpoint will be called. There are two options available:ajax
- the default option where anXMLHttpRequest
object will be used to make a request. The parameters will be passed asPOST
parameters.jsonp
- The authorization endpoint will be called by a<script>
tag being dynamically created pointing to the endpoint defined bychannelAuthorization.endpoint
. This can be used when the authorization endpoint is on a different domain to the web application. The endpoint will therefore be requested as aGET
and parameters passed in the query string.
params
(Object) - Additional parameters to be sent when the channel authorization endpoint is called. When using ajax authorization the parameters are passed as additional POST parameters. When using jsonp authorization the parameters are passed as GET parameters. This can be useful with web application frameworks that guard against CSRF (Cross-site request forgery).headers
(Object) - Only applied when usingajax
as authorizing transport. Provides the ability to pass additional HTTP Headers to the user authorization endpoint. This can be useful with some web application frameworks that guard against CSRF CSRF (Cross-site request forgery).paramsProvider
(Function) - When present, this function is called to get additional parameters to be sent when the user authentication endpoint is called. This is equivalent to passing them on the params key, but allows for the parameters to be retrieved dynamically at the time of the request.headersProvider
(Function) - When present, this function is called to get additional headers to be sent when the user authentication endpoint is called. This is equivalent to passing them on the headers key, but allows for the headers to be retrieved dynamically at the time of the request.customHandler
(Function) - When present, this function is called instead of a request being made to the endpoint specified bychannelAuthorization.endpoint
.
cluster
(String)
Currently only eu
is supported. If you do not specify a cluster, eu
will be used by default. More clusters are coming soon.
const jetsocket = new Jetsocket(APP_KEY, {
cluster: APP_CLUSTER,
});
disableStats
(deprecated) (Boolean)
Disables stats collection, so that connection metrics are not submitted to Jetsocket’s servers. These stats are used for internal monitoring only and they do not affect the account stats. This option is deprecated since stats collection is now disabled by default
enableStats
(Boolean)
Enables stats collection, so that connection metrics are submitted to Jetsocket’s servers. These stats can help jetsocket engineers debug connection issues.
enabledTransports
(Array)
Specifies which transports should be used by jetsocket-js to establish a connection. Useful for applications running in controlled, well-behaving environments. Available transports for web are ws
and wss
.
// Only use WebSockets
const jetsocket = new Jetsocket(APP_KEY, {
cluster: APP_CLUSTER,
enabledTransports: ['ws']
});
Note: if you intend to use secure websockets, or wss
, you can not simply specify wss
in enabledTransports
, you must specify ws
in enabledTransports
as well as set the forceTLS
option to true
.
// Only use secure WebSockets
const jetsocket = new Jetsocket(APP_KEY, {
cluster: APP_CLUSTER,
enabledTransports: ['ws'],
forceTLS: true
});
ignoreNullOrigin
(Boolean)
Ignores null origin checks for HTTP fallbacks. Use with care, it should be disabled only if necessary (i.e. PhoneGap).
activityTimeout
(Integer)
If there is no activity for this length of time (in milliseconds), the client will ping the server to check if the connection is still working. The default value is set by the server. Setting this value to be too low will result in unnecessary traffic.
pongTimeout
(Integer)
Time before the connection is terminated after a ping is sent to the server. Default is 30000 (30s). Low values will cause false disconnections, if latency is high.
Global configuration
Jetsocket.logToConsole
(Boolean)
Enables logging to the browser console via calls to console.log
.
Jetsocket.log
(Function)
Assign a custom log handler for the jetsocket-js library logging. For example:
Jetsocket.log = (msg) => {
console.log(msg);
};
By setting the log
property you also override the use of Jetsocket.enableLogging
.
Connection
A connection to Jetsocket is established by providing your APP_KEY
and APP_CLUSTER
to the constructor function:
const jetsocket = new Jetsocket(APP_KEY, {
cluster: APP_CLUSTER,
});
This returns a jetsocket object which can then be used to subscribe to channels.
One reason this connection might fail is your account being over its' limits. You can detect this in the client by binding to the error
event on the jetsocket.connection
object. For example:
const jetsocket = new Jetsocket('app_key', { cluster: APP_CLUSTER });
jetsocket.connection.bind( 'error', function( err ) {
if( err.data.code === 4004 ) {
log('Over limit!');
}
});
You may disconnect again by invoking the disconnect
method:
jetsocket.disconnect();
Connection States
The connection can be in any one of these states.
State | Note |
---|---|
initialized | Initial state. No event is emitted in this state. |
connecting | All dependencies have been loaded and Channels is trying to connect. The connection will also enter this state when it is trying to reconnect after a connection failure. |
connected | The connection to Channels is open and authenticated with your app. |
unavailable | The connection is temporarily unavailable. In most cases this means that there is no internet connection. It could also mean that Channels is down |
failed | Channels is not supported by the browser. This implies that WebSockets are not natively available and an HTTP-based transport could not be found. |
disconnected | The Channels connection was previously connected and has now intentionally been closed. |
Socket IDs
Making a connection provides the client with a new socket_id
that is assigned by the server. This can be used to distinguish the client's own events. A change of state might otherwise be duplicated in the client.
It is also stored within the socket, and used as a token for generating signatures for private channels.
Subscribing to channels
Public channels
The default method for subscribing to a channel involves invoking the subscribe
method of your jetsocket object:
const channel = jetsocket.subscribe('my-channel');
This returns a Channel object which events can be bound to.
Private channels
Private channels are created in exactly the same way as normal channels, except that they reside in the 'private-' namespace. This means prefixing the channel name:
const channel = jetsocket.subscribe('private-my-channel');
Encrypted Channels
Like private channels, encrypted channels have their own namespace, 'private-encrypted-'.
const channel = jetsocket.subscribe('private-encrypted-my-channel');
Accessing Channels
It is possible to access channels by name, through the channel
function:
const channel = jetsocket.channel('private-my-channel');
It is possible to access all subscribed channels through the allChannels
function:
jetsocket.allChannels().forEach(channel => console.log(channel.name));
Private, presence and encrypted channels will make a request to your channelAuthorization.endpoint
(/jetsocket/auth
) by default, where you will have to authorize the subscription. You will have to send back the correct authorization response and a 200 status code.
Unsubscribing from channels
To unsubscribe from a channel, invoke the unsubscribe
method of your jetsocket object:
jetsocket.unsubscribe('my-channel');
Unsubscribing from private channels is done in exactly the same way, just with the additional private-
prefix:
jetsocket.unsubscribe('private-my-channel');
Binding to events
Event binding takes a very similar form to the way events are handled in jQuery. You can use the following methods either on a channel object, to bind to events on a particular channel; or on the jetsocket object, to bind to events on all subscribed channels simultaneously.
bind
and unbind
Binding to "new-message" on channel: The following logs message data to the console when "new-message" is received
channel.bind('new-message', function (data) {
console.log(data.message);
});
We can also provide the this
value when calling a handler as a third optional parameter. The following logs "hi Jetsocket" when "my-event" is fired.
channel.bind('my-event', function () {
console.log(`hi ${this.name}`);
}, { name: 'Jetsocket' });
For client-events on presence channels, bound callbacks will be called with an additional argument. This argument is an object containing the user_id
of the user who triggered the event
presenceChannel.bind('client-message', function (data, metadata) {
console.log('received data from', metadata.user_id, ':', data);
});
Unsubscribe behaviour varies depending on which parameters you provide it with. For example:
// Remove just `handler` for the `new-comment` event
channel.unbind('new-comment', handler);
// Remove all handlers for the `new-comment` event
channel.unbind('new-comment');
// Remove `handler` for all events
channel.unbind(null, handler);
// Remove all handlers for `context`
channel.unbind(null, null, context);
// Remove all handlers on `channel`
channel.unbind();
bind_global
and unbind_global
bind_global
and unbind_global
work much like bind
and unbind
, but instead of only firing callbacks on a specific event, they fire callbacks on any event, and provide that event along to the handler along with the event data. For example:
channel.bind_global(function (event, data) {
console.log(`The event ${event} was triggered with data ${data}`);
})
unbind_global
works similarly to unbind
.
// remove just `handler` from global bindings
channel.unbind_global(handler);
// remove all global bindings
channel.unbind_global();
unbind_all
The unbind_all
method is equivalent to calling unbind()
and unbind_global()
together; it removes all bindings, global and event specific.
A few gotchas to consider when using client events:
- Client events can only be triggered on private/presence channels
- Client events must be enabled in the settings page for your app:
https://jetsocket.io
- The event name for client events must start with
client-
channel.trigger('client-my-event', {message: 'Hello, world!'})