Javascript client

Simple javascript browser client

Javascript client is very simple. Lets take a look at its API step by step.

When you have Centrifuge instance running - it is time to communicate with it from browser.

First, import javascript client into your web page, the simplest way is just include script tag:

<script src="https://rawgit.com/centrifugal/centrifuge-js/master/centrifuge.js"></script>

Javascript client built on top of Event Emitter written by Oliver Caldwell.

First, create new centrifuge object instance:

var centrifuge = new Centrifuge({
    url: 'http://centrifuge.example.com/connection',
    project: 'PROJECT KEY',
    user: 'USER ID',
    timestamp: 'timestamp',
    token: 'token'
});

url is a Centrifuge endpoint - SockJS or Websocket. Note that in case of using SockJS it must be imported on your page before Centrifuge’s javascript client:

<script src="https://cdn.jsdelivr.net/sockjs/1.0/sockjs.min.js" type="text/javascript"></script>
<script src="https://rawgit.com/centrifugal/centrifuge-js/master/centrifuge.js" type="text/javascript"></script>

In case of using SockJS additional configuration parameter can be used - transports. It defines allowed transports and by default equals [‘websocket’, ‘xdr-streaming’, ‘xhr-streaming’, ‘eventsource’, ‘iframe-eventsource’, ‘iframe-htmlfile’, ‘xdr-polling’, ‘xhr-polling’, ‘iframe-xhr-polling’, ‘jsonp-polling’].

project is project key from Centrifuge. Every project in Centrifuge has unique name (key). You can see it on project settings page of administrative web interface. This is just a string.

user is your web application’s current user unique ID. It must be string and can be empty if you want to allow anonymous access to your real-time application.

timestamp is current UNIX seconds as string. For example for Python str(int(time.time()))

token is a secret key generated by your web application based on project secret key, project key and user ID. Every project in Centrifuge has secret key. You must never show it to anyone else. The only two who know secret key are Centrifuge itself and your web application backend. To create token you must use HMAC algorithm. To understand how to generate client connection token see special chapter Tokens and signatures.

Correct token guarantees that connection request to Centrifuge contains valid information about project key, user ID and timestamp. Token is similar to HTTP cookie, client must not show it to anyone else. Remember that you must always use channels in private namespaces when working with limited access data.

Also you can optionally provide extra parameter info when connecting to Centrifuge:

var centrifuge = new Centrifuge({
    url: 'http://centrifuge.example.com/connection',
    project: 'PROJECT ID',
    user: 'USER ID',
    timestamp: 'timestamp',
    info: '{"first_name": "Alexandr", "last_name": "Emelin"}',
    token: 'token'
});

info is an additional information about user connecting to Centrifuge. It must be valid JSON string. But to prevent client sending wrong info this JSON string must be used while generating token.

If you don’t want to use info - you can omit this parameter while connecting to Centrifuge. But if you omit it then make sure that it have not been used in token generation.

If you are using Python - then you can use generate_token function from cent library to generate tokens for your users.

So, now centrifuge client configured and you are ready to start communicating.

First, we should actually connect to Centrifuge:

centrifuge.connect();

This line makes actual connection request to Centrifuge with data you provided as initialization step.

After successful connect you can subscribe on channels. But you can only start subscribing when connection with Centrifuge was successfully established. If you try to subscribe on channel before connection established - your subscription request will be rejected by Centrifuge. There is an event about successful connection and you can bind your subscription logic to it in this way:

centrifuge.on('connect', function() {
    // now your client connected
});

Also you disconnect and error events available:

centrifuge.on('disconnect', function() {
    // do whatever you need in case of disconnect
});

centrifuge.on('error', function(error_message) {
    // called every time error occurred
});

When your client connected, it is time to subscribe on channel:

var subscription = centrifuge.subscribe('namespace:channel', function(message) {
    // called when message received from this channel
});

If namespace of channel has publish option enabled you can publish messages into this channel. But you can not do it immediately after subscription request. You can only publish when subscribe:success event will be fired. The same in case of presence and history requests. Lets publish message, get presence and get history data as soon as our subscription request returned successful subscription response:

subscription.on('ready', function() {

    // publish into channel
    subscription.publish("hello");

    // get presence information (who is currently subscribed on this channel)
    subscription.presence(function(message) {
        console.log(message);
    });

    // get history (last messages sent) for this channel
    subscription.history (function(message) {
        console.log(message);
    });

    subscription.on('join', function(message) {
        // called when someone subscribes on channel
    });

    subscription.on('leave', function(message) {
        // called when someone unsubscribes from channel
    });

});

You can unsubscribe from subscription:

subscription.unsubscribe();

In some cases you need to disconnect your client from Centrifuge:

centrifuge.disconnect();

After calling this client will not try to reestablish connection periodically. You must call connect method manually.

Starting from Centrifuge 0.5.0 there is an experimental message batching support. It allows to send several messages to Centrifuge in one request - this can be especially usefull when connection established via one of non-streaming HTTP polyfills.

You can start collecting messages to send calling startBatching() method:

centrifuge.startBatching();

When you want to actually send all collected messages to Centrifuge call flush() method:

centrifuge.flush();

Maximum amount of messages in one batching request is 100 (this is by default and can be changed in Centrifuge configuration file using client_api_message_limit option).

Finally if you don’t want batching anymore call stopBatching() method:

centrifuge.stopBatching();

call stopBatching(true) to flush all messages and stop batching.

Version 0.7.0 introduced new `pusher<https://pusher.com/docs/client_api_guide/client_private_channels>`_-like private channel subscription mechanism. Now if channel name starts with $ (by default) then subscription on this channel will be checked via AJAX POST request from javascript to your web application.

You subscribe on private channel as usual:

centrifuge.subscribe('$private', function(message) {
    // process message
});

But in this case client will first check subscription via your backend sending POST request to /centrifuge/auth endpoint (by default). This request will contain client parameter which is your connection client ID and channels parameter - one or multiple private channels client wants to subscribe to. Your server should validate all this subscriptions and return properly signed responses.

There are also two new public API methods in 0.7.0 which can help to subscribe to many private channels sending only one POST request to your web application backend: startAuthBatching and stopAuthBatching. When you startAuthBatching centrifuge js client will collect private subscriptions until stopAuthBatching call - and then send them all at once.

Read more about private channels in special documentation chapter.

Plugins

centrifuge.dom.js - jQuery plugin to use DOM elements to manipulate non dynamic subscriptions.