Giter VIP home page Giter VIP logo

pusher-js's Introduction

Pusher Channels Javascript Client

test badge

This Pusher Channels client library supports web browsers, web workers and Node.js

If you're looking for the Pusher Channels server library for Node.js, use pusher-http-node instead.

For tutorials and more in-depth information about Pusher Channels, visit our official docs.

Usage Overview

The following topics are covered:

Supported platforms

Installation

Web

If you're using Pusher Channels 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 pusher-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 pusher-js

Then:

import Pusher from 'pusher-js';

If you'd like to use encrypted channels:

import Pusher from 'pusher-js/with-encryption';

Or, if you're not using ES6 modules:

const Pusher = require('pusher-js');

If you'd like to use encrypted channels:

const Pusher = require('pusher-js/with-encryption');

CDN

<script src="https://js.pusher.com/7.0/pusher.min.js"></script>

If you'd like to use encrypted channels:

<script src="https://js.pusher.com/7.0/pusher-with-encryption.min.js"></script>

You can also use cdnjs.com if you prefer or as a fallback.

Bower (discouraged)

Or via Bower:

bower install pusher

and then:

<script src="bower_components/pusher/dist/web/pusher.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 Pusher from 'pusher-js';
import * as PusherTypes from 'pusher-js';

var presenceChannel: PusherTypes.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

(pusher-js's Web Workers implementation is currently not compatible with Internet Explorer) You can import the worker script (pusher.worker.js, not pusher.js) from the CDN:

importScripts('https://js.pusher.com/7.0/pusher.worker.min.js');

If you'd like to use encrypted channels:

importScripts('https://js.pusher.com/7.0/pusher-with-encryption.worker.min.js');

If you're building your worker with a bundler, you can import the worker entrypoint

import Pusher from 'pusher-js/worker'

If you'd like to use encrypted channels:

import Pusher from 'pusher-js/worker/with-encryption'

Node.js

Having installed pusher-js via an NPM-compatible package manager, run:

import Pusher from 'pusher-js';

Notes:

  • For standard WebWorkers, this build will use HTTP as a fallback.
  • For ServiceWorkers, as the XMLHttpRequest API is unavailable, there is currently no support for HTTP fallbacks. However, we are open to requests for fallbacks using fetch if there is demand.

Initialization

const pusher = new Pusher(APP_KEY, {
  cluster: APP_CLUSTER,
});

You can get your APP_KEY and APP_CLUSTER from the Pusher Channels dashboard.

Configuration

There are a number of configuration parameters which can be set for the client, which can be passed as an object to the Pusher constructor, i.e.:

const pusher = new Pusher(APP_KEY, {
  cluster: APP_CLUSTER,
  channelAuthorization: {
    endpoint: 'http://example.com/pusher/auth'
  },
});

For most users, there is little need to change these. See client API guide for more details.

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 /pusher/user-auth.

  • transport (String) - Defines how the authentication endpoint will be called. There are two options available:

    • ajax - the default option where an XMLHttpRequest object will be used to make a request. The parameters will be passed as POST parameters.
    • jsonp - The authentication endpoint will be called by a <script> tag being dynamically created pointing to the endpoint defined by userAuthentication.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 a GET 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 using ajax 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 by userAuthentication.endpoint.

For more information see authenticating users.

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 /pusher/auth.

  • transport (String) - Defines how the authorization endpoint will be called. There are two options available:

    • ajax - the default option where an XMLHttpRequest object will be used to make a request. The parameters will be passed as POST parameters.
    • jsonp - The authorization endpoint will be called by a <script> tag being dynamically created pointing to the endpoint defined by channelAuthorization.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 a GET 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 using ajax 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 by channelAuthorization.endpoint.

For more information see authorizing users.

cluster (String)

Specifies the cluster that pusher-js should connect to. If you'd like to see a full list of our clusters, click here. If you do not specify a cluster, mt1 will be used by default.

const pusher = new Pusher(APP_KEY, {
  cluster: APP_CLUSTER,
});

disableStats (deprecated) (Boolean)

Disables stats collection, so that connection metrics are not submitted to Pusher’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 Pusher’s servers. These stats can help pusher engineers debug connection issues.

enabledTransports (Array)

Specifies which transports should be used by pusher-js to establish a connection. Useful for applications running in controlled, well-behaving environments. Available transports for web: ws, wss, xhr_streaming, xhr_polling, sockjs. If you specify your transports in this way, you may miss out on new transports we add in the future.

// Only use WebSockets
const pusher = new Pusher(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 pusher = new Pusher(APP_KEY, {
  cluster: APP_CLUSTER,
  enabledTransports: ['ws'],
  forceTLS: true
});

disabledTransports (Array)

Specifies which transports must not be used by pusher-js to establish a connection. This settings overwrites transports whitelisted via the enabledTransports options. Available transports for web: ws, wss, xhr_streaming, xhr_polling, sockjs. This is a whitelist, so any new transports we introduce in the future will be used until you explicitly add them to this list.

// Use all transports except for sockjs
const pusher = new Pusher(APP_KEY, {
  cluster: APP_CLUSTER,
  disabledTransports: ['sockjs']
});

// Only use WebSockets
const pusher = new Pusher(APP_KEY, {
  cluster: APP_CLUSTER,
  enabledTransports: ['ws', 'xhr_streaming'],
  disabledTransports: ['xhr_streaming']
});

wsHost, wsPort, wssPort, httpHost, httpPort, httpsPort

These can be changed to point to alternative Pusher Channels URLs (used internally for our staging server).

wsPath

Useful in special scenarios if you're using the library against an endpoint you control yourself. This is used internally for testing.

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

Pusher.logToConsole (Boolean)

Enables logging to the browser console via calls to console.log.

Pusher.log (Function)

Assign a custom log handler for the pusher-js library logging. For example:

Pusher.log = (msg) => {
  console.log(msg);
};

By setting the log property you also override the use of Pusher.enableLogging.

Connection

A connection to Pusher Channels is established by providing your APP_KEY and APP_CLUSTER to the constructor function:

const pusher = new Pusher(APP_KEY, {
  cluster: APP_CLUSTER,
});

This returns a pusher 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 pusher.connection object. For example:

const pusher = new Pusher('app_key', { cluster: APP_CLUSTER });
pusher.connection.bind( 'error', function( err ) {
  if( err.data.code === 4004 ) {
    log('Over limit!');
  }
});

You may disconnect again by invoking the disconnect method:

pusher.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. More information on this pattern is available here.

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 pusher object:

const channel = pusher.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 = pusher.subscribe('private-my-channel');

Encrypted Channels

Like private channels, encrypted channels have their own namespace, 'private-encrypted-'. For more information about encrypted channels, please see the docs.

const channel = pusher.subscribe('private-encrypted-my-channel');

Accessing Channels

It is possible to access channels by name, through the channel function:

const channel = pusher.channel('private-my-channel');

It is possible to access all subscribed channels through the allChannels function:

pusher.allChannels().forEach(channel => console.log(channel.name));

Private, presence and encrypted channels will make a request to your channelAuthorization.endpoint (/pusher/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 pusher object:

pusher.unsubscribe('my-channel');

Unsubscribing from private channels is done in exactly the same way, just with the additional private- prefix:

pusher.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 pusher 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 Pusher" when "my-event" is fired.

channel.bind('my-event', function () {
  console.log(`hi ${this.name}`);
}, { name: 'Pusher' });

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.

Triggering Client Events

It's possible to trigger client events using the trigger method on an instance of the Channel class.

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://dashboard.pusher.com/apps/$YOUR_APP_ID/settings
  • The event name for client events must start with client-
channel.trigger('client-my-event', {message: 'Hello, world!'})

Batching authorization requests (aka multi-authorization)

Currently, pusher-js itself does not support authorizing multiple channels in one HTTP request. However, thanks to @dirkbonhomme you can use the pusher-js-auth plugin that buffers subscription requests and sends authorization requests to your endpoint in batches.

Default events

There are a number of events which are used internally, but can also be of use elsewhere, for instance subscribe. There is also a state_change event - which fires whenever there is a state change. You can use it like this:

pusher.connection.bind('state_change', function(states) {
  // states = {previous: 'oldState', current: 'newState'}
  $('div#status').text("Channels current state is " + states.current);
});

Connection Events

To listen for when you connect to Pusher Channels:

pusher.connection.bind('connected', callback);

And to bind to disconnections:

pusher.connection.bind('disconnected', callback);

Self-serving JS files

You can host JavaScript files yourself, but it's a bit more complicated than putting them somewhere and just linking pusher.js in the source of your website. Because pusher-js loads fallback files dynamically, the dependency loader must be configured correctly or it will be using js.pusher.com.

First, clone this repository and run npm install && git submodule init && git submodule update. Then run:

$ CDN_HTTP='http://your.http.url' CDN_HTTPS='https://your.https.url' make web

In the dist/web folder, you should see the files you need: pusher.js, pusher.min.js, json2.js, json.min.js, sockjs.js and sockjs.min.js. pusher.js should be built referencing your URLs as the dependency hosts.

First, make sure you expose all files from the dist directory. They need to be in a directory with named after the version number. For example, if you're hosting version 7.0.0 under http://example.com/pusher-js (and https for SSL), files should be accessible under following URL's:

http://example.com/pusher-js/7.0.0/pusher.js
http://example.com/pusher-js/7.0.0/json2.js
http://example.com/pusher-js/7.0.0/sockjs.js

Minified files should have .min in their names, as in the dist/web directory:

http://example.com/pusher-js/7.0.0/pusher.min.js
http://example.com/pusher-js/7.0.0/json2.min.js
http://example.com/pusher-js/7.0.0/sockjs.min.js

SockJS compatibility

Most browsers have a limit of 6 simultaneous connections to a single domain, but Internet Explorer 6 and 7 have a limit of just 2. This means that you can only use a single Pusher Channels connection in these browsers, because SockJS requires an HTTP connection for incoming data and another one for sending. Opening the second connection will break the first one as the client won't be able to respond to ping messages and get disconnected eventually.

All other browsers work fine with two or three connections.

Developing

Install all dependencies via Yarn:

yarn install

Run a development server which serves bundled javascript from http://localhost:5555/pusher.js so that you can edit files in /src freely.

make serve

You can optionally pass a PORT environment variable to run the server on a different port. You can also pass CDN_HTTP and CDN_HTTPS variables if you wish the library to load dependencies from a new host.

This command will serve pusher.js, sockjs.js, json2.js, and their respective minified versions.

Core Vs. Platform-Specific Code

New to pusher-js 3.1 is the ability for the library to produce builds for different runtimes: classic web, NodeJS and Web Workers.

In order for this to happen, we have split the library into two directories: core/ and runtimes/. In core we keep anything that is platform-independent. In runtimes we keep code that depends on certain runtimes.

Throughout the core/ directory you'll find this line:

import Runtime from "runtime";

We use webpack module resolution to make the library look for different versions of this module depending on the build.

For web it will look for src/runtimes/web/runtime.ts. For ReactNative, src/runtimes/react-native/runtime.ts. For Node: src/runtimes/node/runtime.ts. For worker: src/runtimes/worker/runtime.ts.

Each of these runtime files exports an object (conforming to the interface you can see in src/runtimes/interface.ts) that abstracts away everything platform-specific. The core library pulls this object in without any knowledge of how it implements it. This means web build can use the DOM underneath, the ReactNative build can use its native NetInfo API, Workers can use fetch and so on.

Building

In order to build SockJS, you must first initialize and update the Git submodule:

git submodule init
git submodule update

Then run:

make web

This will build the source files relevant for the web build into dist/web.

In order to specify the library version, you can either update package.json or pass a VERSION environment variable upon building.

Other build commands include:

make node         # for the NodeJS build
make worker       # for the worker build

Testing

Each test environment contains two types of tests:

  1. unit tests,
  2. integration tests.

Unit tests are simple, fast and don't need any external dependencies. Integration tests usually connect to production and js-integration-api servers and can use a local server for loading JS files, so they need an Internet connection to work.

There are 3 different testing environments: one for web, one for NodeJS and one for workers.

The web and worker tests use Karma to execute specs in real browsers. The NodeJS tests use jasmine-node.

To run the tests:

# For web
make web_unit
make web_integration

# For NodeJS
make node_unit
make node_integration

# For workers
make worker_unit
make worker_integration

If you want your Karma tests to automatically reload, then in spec/karma/config.common.js set singleRun to false.

pusher-js's People

Contributors

amad avatar aodinok avatar benpickles avatar damdo avatar danielwaterworth avatar dependabot[bot] avatar dirkbonhomme avatar ejlangev avatar fbenevides avatar hph avatar ismasan avatar jameshfisher avatar jpatel531 avatar kn100 avatar leesio avatar leggetter avatar maryrosecook avatar mdpye avatar meenaalfons avatar miksago avatar mloughran avatar pl avatar pusher-ci avatar sonologico avatar stof avatar thegoncalomartins avatar wildfalcon avatar willpusher avatar willsewell avatar zimbatm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pusher-js's Issues

Server response data format

In response for subscription event, Pusher server sends "data" as json string.
It seems strange, because response is already json-string.
example response:
{"event":"pusher_internal:subscription_succeeded","data":"{"presence":{"count":1,"ids":["462127"],"hash":{"462127":{"first":"Oleje","last":"Teleje"}}}}","channel":"presence-demo"}

Data attribute is escaped, and other attributes not.
Why use json-string inside json-string?

Disconnect error - missing hasOwnProperty check

The disconnect method throws an error if the object prototype has been extended. code requires a if hasOwnProperty check as below. The unsubscribe method has this check.

1034:
disconnect: function(){
for (var channel_name in this.channels) {
if (this.channels.hasOwnProperty(channel_name))
this.channels[channel_name].disconnect()
}
}

Uncaught TypeError: Cannot call method 'supportsPing' of null

Our pusher implementation is pretty simple. We use the 2.0 client and the following code to initialise:

var CHANNEL_ID = '...';
var PUSHER_KEY = '...';
var pusher = new Pusher(PUSHER_KEY, { encrypted: true, disableFlash: true });
var channel = pusher.subscribe(CHANNEL_ID);
channel.bind('myEvent', function(data) { ... } );

This is the error we've seen (and the line where it's thrown):

Uncaught TypeError: Cannot call method 'supportsPing' of null

this.unavailableTimer = setTimeout(function() {
e.unavailableTimer && (e.updateState("unavailable"), e.unavailableTimer = null);
}, this.options.unavailableTimeout);
}, t.clearUnavailableTimer = function() {
this.unavailableTimer && (clearTimeout(this.unavailableTimer), this.unavailableTimer = null);
}, t.resetActivityCheck = function() {
this.stopActivityCheck();
if (!this.connection.supportsPing()) { <===================== error thrown here
var e = this;
this.activityTimer = setTimeout(function() {
e.send_event("pusher:ping", {}), e.activityTimer = setTimeout(function() {
e.connection.close();

I haven't reproduced this on my computer, but it's happened for our customers (Chrome 25) and we get the reports via our onError tracking.

Hopefully this is enough to investigate, otherwise feel free to close the issue.

Handling multiple presence channels over a single pusher connection

Hi all,
I'm not sure if this problem is due to me or it's a bug, I just write it hoping it's not my fault

I have a single pusher encrypted connection:

api_key = '..';
channels = {};
pusher = new Pusher(api_key, {encrypted: true,
                                        auth: {
                                          headers: {
                                            'X-CSRF-Token': $('meta[name=csrf-token]').first().attr('content')
                                          }
                                        }
                                      });

and I use it to subscribe to N presence channels (in my example they are 2):

jQuery('.room').each(function(){
  single_room = jQuery(this);
  room_id = single_room.attr('id');
  // I have channel's name in html data-channel attribute
  room_channel = single_room.data('channel');
  channels[room_id] = pusher.subscribe(room_channel);
});

I set up events like:

// New message
channels[room_id].bind('message-sent', function(data) {
  console.log("Arrived new data on channel " + room_id + " (next line)");
  console.log(data);
  // Do stuff
});

The problem is that if server-side I send a message to 'room1', on client-side the event "message-sent" fires 2 times, it fires for 'room1' AND for 'room2' with same data.
So in console I see:

Arrived new data on channel room1 (next line)
[data foo]
Arrived new data on channel room2 (next line)
[data foo]

while I would expect to see the event firing only on 'room1'

Connection state not changed on Windows

Hi,

I have a chat app that opens a channel to Pusher and then listens to new events with Javascript on client side.

I bind Pusher to "state_change" event:
pusher.connection.bind("state_change", this.onConnectionStateChange);

When the connection status is different from "connected" (is_connecting, disconnected, unavailable…) I want to notify my users about this.
The state change event is working perfectly on Mac in Chrome, FF and Safari.
On Windows the state change event seems not to work. Even if I disconnect my PC from the Internet, Pusher still thinks that the Web Socket is connected.

I attached a screencast with the Pusher debug bellow:
http://www.screencast.com/t/SVFvYZXBvh

Can you tell me please if this is a common issue and if I can solve it somehow?
Can I ping my Pusher channel from time to time to see if the connection is alive?

Thank you.

Way to pass CSRF token on authenticate?

Right now I have to use a slightly modified version of pusher.js instead of the hosted one, as right now pusher does not set "X-CSRF-Token" which is required by my rails app. I'm not entirely sure what the best way to do this on a global level would be, but I added a line like this to make it work:

xhr.setRequestHeader("X-CSRF-Token", Pusher.csrf_token)

(and set Pusher.csrf_token = $('meta[name="csrf-token"]').attr('content') before calling pusher init).

Open sourcing the state machine?

It wouldn't be possible to open source the little state machine (+ it's attached event system)? I really like it's petite elegance.

global variables in pusher.js

pusher.js uses module structure, but there is one place (I found only one) where global variable is defined (see protocol.js)

In some cases (when window.Protocol is already defined or code is executed in environment where global context is immutable) pusher.js doesn't work properly.

Presence channel does not trigger member_added

For the past 4-5 days, the member_added event is not being triggered when the new member joins in the channel. Below are the events that are received:

Pusher : Event recd : {"event":"pusher_internal:subscription_succeeded","data":{"presence":{"count":1,"ids":["tejinder"],"hash":{"tejinder":{"image":{"url":"/media/images/placeholder.png"}}}}},"channel":"presence-test34"}
Pusher : Event recd : {"event":"sketch-stroke","data":{"value":"[]"},"channel":"presence-test34"}
Pusher : Event sent : {"event":"pusher:ping","data":{}}
Pusher : Event recd : {"event":"pusher:pong","data":{}}

Allow auth endpoint to use basic authentication

We authorize pusher by hitting up an endpoint on our API, the API uses HTTP basic auth and currently we need to make an exception for pusher - passing the authentication in query string.

Is there a way I could pass in extra headers to the auth request?

Presence Channel userInfo not available?

From the docs (http://pusher.com/docs/authenticating_users#/lang=py-gae) it says that you can add user info to the auth response. It should be accessible in client via

presenceChannel.bind('pusher:subscription_succeeded', function() {
  var me = presenceChannel.members.me;
  var userId = me.id;
  var userInfo = me.info;
});

http://pusher.com/docs/client_api_guide/client_presence_channels#pusher-member-added

However it seems that the userInfo is missing for the user (always null). Looking at presence_channel.js line:34 it only saves the channelData.user_id and nothing else. Is this a bug and should it save the userinfo as well? or did I miss something?

Thanks for your help

IE 9 not working

sometimes log shows its connecting with flash parameter set to true:
LOG: Pusher : Connecting : ws://ws.pusherapp.com:80/app/bfc6fe05c3284b947f90?protocol=5&client=js&version=1.12.4&flash=true

sometimes it will show with flash set to false, which is bound to fail as the browser does not support websocket protocol:

LOG: Pusher : Connecting : ws://ws.pusherapp.com:80/app/bfc6fe05c3284b947f90?protocol=5&client=js&version=1.12.4&flash=false

And also sometimes i get security error and connection time outs using SSL protocol. Please resolve these issues. It almost make pusher on IE unusable.

modifying the document object on android 3.2 prevents pusher object from connecting

Testpage which tries to connect to pusher. Works on all devices except on android 3.2 stock browser. (gets a unavaillable state change).

I think that the problem is the document object manipulation ? If you change the document.write to an alert, no problem at all.

I ran against this problem with our code dynamically injecting an audio tag in the document, this also broke the pusher connection.

<!DOCTYPE html>
<head>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  <script src="http://js.pusher.com/2.1/pusher.min.js"></script>
  <script>
    (function($){
     Pusher.log = function(message){
      // This code fails on android 3.2 (GT-P6210) stock browser (gets a state change to unavailable)
      // If you change the document.write to an alert, the pusher object can connect without any problem
      document.write("pusher message " + message + "<br/>") 
     }
     var pusher = new Pusher('apikey');
     pusher.connection.bind('state_change', function(states){
      alert("Pusher State change " + states.current);
     })
    })(jQuery);
  </script>
</head>
<body>
  <h1>pusher and document manipulation on android 3.2</h1>
</body>

Does not work in IE9

Note: IE9 does not currently contain WebSockets.

When accessing http://pushertest.heroku.com/1.7.4-pre, pusher does not log anything

It may be that this is caused by the asynchronous dependency loading. To rule that out I tried http://pushertest.heroku.com/1.6.1 which loads all dependencies together. However there is an error with

if (window.console) window.console.log.apply(window.console, arguments);

"'arguments' is undefined"

Maybe there are two separate issues?

Call to `setTimeout` which is undefined in Mobile Safari 6

We're seeing an TypeError: 'undefined' is not an object in Mobile Safari 6 (iPad and iPhone).

This is where the error occurs:

if (this.state === "open") {
    var t = this;
    return setTimeout(function() {
        t.socket.send(e);
    }, 0), !0;
}

User agents:

  • Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25
  • Mozilla/5.0 (iPad; CPU OS 6_1_2 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B146 Safari/8536.25

support to force Flash fallback

Hi there,

I've run into an odd problem with some clients. They are behind a firewall which prevents websocket connections. Because the transport type is based on feature detection, they get setup to connect via native websockets which can't properly connect and the Flash fallback doesn't load.

I've written a proof-of-concept that prevents this from happening by redefining the properties Pusher looks at for feature detection and thus forcing the fallback. However, this is sloppy and only works in some browsers.

I'm planning to improve on this by adding a configuration parameter that can be set to force the fallback connection. It will be checked alongside the various properties used for feature detection. This is still going to be less than elegant but it will work and won't appreciably change the current Pusher startup process.

I don't know if there is wider interest in this, and I'm not expecting my changes to be incorporated upstream. However, if anyone wants to suggest a better approach I would be interested in hearing it.

Private channel demo

It would be nice to have a demo showing how to subscribe to a private channel and trigger client events, including what the server side behind 'Pusher.channel_auth_endpoint' is supposed to do.

In addition, the README is wrongly referring to Pusher.auth_url instead of Pusher.channel_auth_endpoint.

Thanks,

Add bower support

It's a very realistic possibility that some users will want to use a package manager like bower to install a copy of Pusher.js locally. For example, to create a local fallback copy of Pusher in case the CDN is down.

What we need to do (from the bower README):

  • There must be a valid manifest JSON in the current working directory.
  • Your package should use semver Git tags.
  • Your package must be available at a Git endpoint (e.g., GitHub); remember to push your Git tags!

(https://github.com/bower/bower)

Multi authentication

Our application needs to authenticate upto 40 private channels on load, our server side auth endpoint can obviously handle this with no problem but how should it be approached from the POV of the JS library?

I'm finding a lot of mixed information across the internet and no solid examples of how to achieve this. I don't want to have to monkey patch the client lib?

Connection problems (state_change and long running connection)

This issue represents problems with the connection to Pusher from the JavaScript library:

  1. state_change events not being triggered after sleep
  2. Connection seeming to be lost and no messages being sent after an application has been open for a reasonable amount of time.

Related issues:


pusher.connection.bind('state_change', function(states) {
    // states = {previous: 'oldState', current: 'newState'}
    $('span#status').html(" [<span class='" + states.current + "'>" + states.current + "</span>]");
});

if I put my laptop to sleep for the night and wake it up in the morning, the status never refreshes. I thought these events would handle that.

Further details can be found in the following support issue (requires permissioned login): https://pusher.tenderapp.com/discussions/questions/297-state_change-event-does-not-fire-when-connection-is-lost

Extend event binding with optional context

It's common to add a third "context" argument when binding event handlers in Backbone and many other frameworks. This way you can avoid .bind() on all your callbacks and it eases unbinding:

http://backbonejs.org/#Events-on

// Removes just the `onChange` callback.
object.off("change", onChange);

// Removes all "change" callbacks.
object.off("change");

// Removes the `onChange` callback for all events.
object.off(null, onChange);

// Removes all callbacks for `context` for all events.
object.off(null, null, context);

// Removes all callbacks on `object`.
object.off();

Or when applied to Pusher:

{
    initialize: function(){
        var channel = pusher.subscribe('my-channel');
        channel.bind('lorem-ipsum', this.handleLipsum, this);
        channel.bind('foo-bar', this.handleBar, this);
    },

    teardown: function(){
        channel.unbind(null, null, this);
    }
}

This will remain compatible with the current implementation. Would you be interested in a PR for this feature? I'm prepared to add it to the codebase but don't want to maintain a separate fork..

pusher:member_removed is not triggered while using multiple presence channels

I'm using multiple presence channels. When the user closes the connection (by closing the browser tab, for example), pusher_internal:member_removed event occurs on all channels, but only one dispatches pusher:member_removed event.

While debugging at

this.bind('pusher_internal:member_removed', function(data){
      var member = this.members.remove(data.user_id);
      if (member) {
        this.dispatch_with_all('pusher:member_removed', member);
      }
    }.scopedTo(this))

I've noticed that the member is null, but it does not make sense to me, because the user was subscribed to the channel, so he should be included on channel's members.

I maybe wrong, but I think that when the user is unsubscribed from the first channel, he is removed from ALL channels. So when pusher tries to remove him from the others channels he is not there anymore and member is null

What do you think is it?

Pusher's log output:

["Pusher : event recd (channel,event,data)", "presence-user-2", "pusher_internal:member_removed", Object]
["Pusher : event recd (channel,event,data)", "presence-user-2", "pusher:member_removed", Object]
["Pusher : No callbacks for pusher:member_removed"]
["Pusher : event recd (channel,event,data)", "presence-user-1", "pusher_internal:member_removed", Object]
["Pusher : event recd (channel,event,data)", "presence-user-3", "pusher_internal:member_removed", Object]
["Pusher : event recd (channel,event,data)", "presence-user-4", "pusher_internal:member_removed", Object]

Allow only specific members to trigger client events

Hi, I have the following use case:

  • A private channel is created for a set of users.
  • One member is responsible for broadcasting events.
  • The rest of the members only receive events.

This is what I'm doing currently to trigger an event:

  • An ajax call is made to my server.
  • The server checks that the user is allowed to broadcast.
  • If user is allowed, pusher server api is used to broadcast the event to all users.

What I'm doing is a bit slow (average 1-2 seconds) due to latency, server warm up, etc.

Using client events would make the whole process faster. The problem with client events is that there is no way to specify which members are allowed to broadcast events.

Would you consider extending the security model around client events?

As a first idea, I propose to extend the authentication mechanism:

  • When the server responds to /pusher/auth/ step 6 of your diagram, add a field to specify the channel names where the user can trigger client events. The field will be hashed like the auth field.
  • Then, when a user tries to trigger a client event, pusher server validates that is allowed to do so.

Bind to the online & offline event with addEventListener

Instead of setting the handler of both the offline and online events using the ononline & onoffline properties of the window use addEventListener.

This allows pusher's connection status to work even if some other code has changed the value of the ononline & onoffline properties on the window.

Client gives up on websocket and switches to fallback after a loss of internet connectivity

I'm not sure if this behaviour is part of the intended fallback strategy, but it seems a bit odd to me.

  1. A connection is successfully made via websocket.
  2. Internet connectivity is lost for some period of time.
  3. Internet connectivity is regained again.
  4. Connection is reopened using sock.js instead of websockets.

If a connection has successfully been made using websockets, why ever use fallbacks? Why not reconnect via websocket after connectivity is regained?

No error code for WebSocketError

When the client tries to subscribe to a previously subscribed channel the client receives an error event.

{
    "type": "WebSocketError",
    "error": {
        "type": "PusherError",
        "data": {
            "code": null,
            "message": "Existing subscription to channel presence-ABCDE"
        }
    }
}

The code is null which makes it hard to respond to the error.

Could there be an error code attached to this event?

Stale connection goes undetected in pusher-js 1.12

Hi,

I'm doing tests with this code:

<!DOCTYPE html>
<head>
  <title>Pusher Test</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
  <script src="http://js.pusher.com/1.12/pusher.min.js" type="text/javascript"></script>
<script type="text/javascript">
  $(document).ready(function() {
  Pusher.activity_timeout = 500;
  Pusher.pong_timeout = 500;
    var status = function(st) {
      $('#status').text(st);
    }
    // Enable pusher logging - don't include this in production
    Pusher.log = function(message) {
      if (window.console && window.console.log) window.console.log(message);
    };
    // Flash fallback logging - don't include this in production
    WEB_SOCKET_DEBUG = true;
Pusher.channel_auth_endpoint = '/app_dev.php/pusher/auth/';
    var pusher = new Pusher('MY_KEY', { encrypted: true });
    var channel = pusher.subscribe('presence-test_channel');
    channel.bind('my_event', function(data) {
      alert(data);
    });
      pusher.connection.bind('state_change', function(state) {
        status(state.current)
      })
      pusher.connection.bind('state_change', function(state) {
        status(state.current)
      })
  })
</script>
</head>
<body>
  Connection status: <strong><span id="status">unloaded</span></strong>
</body>
</html>

When I run this code, in the debug console on pusher, everything is fine: the client connects and subscribes to the presence-channel. But if I unplug my ethernet / close my laptop's lid / turn off wifi, there is no disconnection message in the debug console, even after a few minutes. I tried setting Pusher.activity_timeout and Pusher.pong_timeout to very low values (500 as you can see) but it doesn't help.
In my browser's javascript console, I can see ping/pong messages being sent. When I cut the connection, it doesn't seem to bother the server that much. Even though my webpage now reads "unavailable" (I print the current status connection).

I'm using Chrome (last release), OSX ML, Pusher 1.12. Same bug appears with firefox (last release) and safari.

`NetInfo.isOnline` is incorrect

I've had probably the worst customer experience with your support over the last few days, so I'm just going to file an issue here and hope someone else can take a look.

https://github.com/pusher/pusher-js/blob/master/src/net_info.js#L26-40 is just plain wrong

If window.navigator.onLine === false, that does NOT mean the connection is definitely offline. The comment above that function Offline means definitely offline (no connection to router). is wrong.

See http://crbug.com/124069. The Google Docs team even has numbers in there for a 24 hour experiment and the rate of false positives at comment 13 http://crbug.com/124069#c13

Is localStorage.pusherTransport ever removed?

I'm not entirely sure, but it appears that localStorage.pusherTransport is never removed, even though this value isn't used anymore in the latest library. Is that done on purpose?

Error `INVALID_STATE_ERR` thrown repeatedly in Firefox 19

Line 60 in https://d3dy5gmtp8yhk7.cloudfront.net/2.0.1/sockjs.min.js
Full error message: Error: INVALID_STATE_ERR

Brower
Occured in Firefox 19 (Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:19.0) Gecko/20100101 Firefox/19.0).

Timing
The error occured 500 times within the span of a few minutes, in bursts of ~50 during a single second. E.g. it happened about fifty times at Fri Apr 12 2013 11:03:59 (CEST) [if that helps you locate this in your logs].

Channel id
4db925d1c36e3c4ec5000002

Other possible contributing factors
Was running Screenleap (http://www.screenleap.com/). It's a Java applet, don't know if that could have any effect. Sounds unlikely but could be.

1.8 passes null member on add/remove?

The 1.8 release, while spiffy, seems to break member_added + member_removed (on Chrome, at least). I can see in the debug that there is an id etc in internal:member_added/removed, but a null object is passed to my callback function. 1.7.4 works fine with equivalent code.

Subscription persists even after (manually calling) unsubscribe

Hi all,

We observed that the only time the member is unsubscribed and removed from a channel is when the browser is closed or the page is reloaded. The app that we're working on is a Single-page Application using Backbone.js so we have to call unsubscribe function manually if we want to unsubscribe. We did but without any luck. The member is still subscribed and the 'member_removed' event was not triggered.

Here's our code snippet

unlisten: function() {
  if (this.active_channel_id != null) {
    this.pusher.unsubscribe(this.active_channel_id);
  }
}

Maybe you guys can help us out in figuring out how unsubscribe function work.

Thanks!

Disconnection state to triggered in 2.1.4 ?

I think the state behaviour changed from 2.1.3 to 2.1.4

In 2.1.3 when pusher disconnected this callback got executed almost immediately.
pusher.connection.bind('disconnected', callback);

In 2.1.4 the disconnected this callback does not get called. It looks like pusher skips the disconnected state and changes to connecting but only after some time (5-15 sec when i tested it by removing my ethernet cable).

This code indicates pusher now skips the disconnected state.

pusher.connection.bind('state_change', function(states) {
    console.log(states);
});

Is that preferable? It's not according to the docs:

If an internet connection disappears
connected -> disconnected -> connecting -> unavailable (after ~ 30s)

'failed' connection state is not triggered

When I test my application in IE with flash disabled, the 'failed' connection state is not triggered, which doesn't allow me to display a sympathy message for my users that don't have Flash (or wrong version) or WebSockets.

The code I was using at the beginning is this:

pusher.connection.bind('failed', function() {
  alert('not supported');
});

And when I was trying to debug a little further I tried to bind the 'state_change' event:

pusher.connection.bind('state_change', function(states) {
  // states = {previous: 'oldState', current: 'newState'}
  alert("Pusher's current state is " + states.current);
});

Which does what is suppose in Safari or IE with Flash but doesn't output anything in IE without Flash.

Does anyone have a working example that the 'failed' state is triggered?

Ability to disable sockjs fallback

We like Pusher, it's awesome!

What's also awesome is that web sockets is supported in the latest version of IE, FF, Chrome, iOS and Android. Hence, we don't need the fallbacks and because of that we can also skip the dependency loading pain.

It would be great if sockjs could be disabled similar to the flash fallback.

var pusher = new Pusher(PUSHER_KEY, { disableFlash: true, disableSockjs: true });

We're doing this right now, which seems to work, but that could change with an update to the client so an option would be great.

Pusher.SockJSTransport.isSupported = function() { return false; };

Include dist with repository

Hey, it would be massively convenient to have the built library included in the repo like say Lodash or a lot of other libs.

It's easier for CI and the build process has too many dependencies (can't even build on certain machines).

What do you think?

Authentication should support CORS

I am going to be brief with my bug report. If you need a more thorough description, let me know.

I am assuming that to properly handle the client's request to /pusher/auth I need to use cookies.

I expected that I could have pusher-js authenticate against my backend HTTP service across origins. I realized that the requests to /pusher/auth did not contain any cookies. Upon further inspection, I found that the pusher-js makes a new XHR object to send to the authentication endpoint of my service. This XHR object does not touch the withCredentials field which, I believe, is required for CORS.

My request is that you provide support for authenticating across origins. Perhaps that is by setting the withCredentials field.

“Existing subscription to channel” while only subscribing once

As posted on http://stackoverflow.com/questions/17833502/existing-subscription-to-channel-while-only-subscribing-once

I have a small snippet that throws an "Existing subscription to channel" exception even though I only call the subscribe method once.

This can be avoided by moving the subscribe request outside of the "state_change" handler, but I'm wondering what might cause this? Maybe a bug in the Pusher library?

<!doctype html>
<html>
<body>
    <h1>Pusher subscribe testcase</h1>
    <p>Tip: check your console</p>
    <script src="https://d3dy5gmtp8yhk7.cloudfront.net/2.1/pusher.min.js"></script>
    <script>
        var pusher, channel;
        pusher = new Pusher('xxxxxxxxxxxxxxxxx');
        pusher.connection.bind('state_change', function(change){
            if(change.current === 'connected'){
                console.log('connected');
                channel = pusher.subscribe('test-channel');
                channel.bind('pusher:subscription_succeeded', function() {
                    console.log('subscribed');
                });
            }
        })
    </script>
</body>
</html>

This results in:

connected
subscribed
Pusher : Error : {"type":"WebSocketError","error":{"type":"PusherError","data":{"code":null,"message":"Existing subscription to channel test-channel"}}}

Uncaught TypeError: Cannot read property 'host' of undefined

I'm seeing this regularly with the latest client (v2.1.2) - it happens when a client becomes disconnected from the internet and seems to be something to do with the JSONP fallback.

Definitely an annoying issue that's filling our server side JS logs. As it appears in the client:

screenshot 2013-10-10 11 48 28

Browser runtime required?

Hi,

The library appears to assume that it is running in the context of a browser. I wonder if it would be feasible to make it agnostic with respect to the runtime so that you could, for instance, load the library in a NodeJS app.

For example in a nodejs application if you say:

Pusher = require('./pusher.min.js');

you get this error:

TypeError: Cannot set property 'EventsDispatcher' of undefined

Perhaps this would better be done as a NodeJS client library...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.