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.
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;
...
Use a package manager like Yarn or NPM to install pusher-js and then import
it as follows:
importPusherfrom'pusher-js/react-native';
Notes:
The fallbacks available for this runtime are HTTP streaming and polling.
This build uses React Native's NetInfo API to detect changes on connectivity state. It will use this to automatically reconnect.
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:
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:
importPusherfrom'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.
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).
customHandler (Function) - When present, this function is called instead of a request being made to the endpoint specified by userAuthentication.endpoint.
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/user-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).
customHandler (Function) - When present, this function is called instead of a request being made to the endpoint specified by channelAuthorization.endpoint.
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 WebSocketsconstpusher=newPusher(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 WebSocketsconstpusher=newPusher(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 sockjsconstpusher=newPusher(APP_KEY,{cluster: APP_CLUSTER,disabledTransports: ['sockjs']});// Only use WebSocketsconstpusher=newPusher(APP_KEY,{cluster: APP_CLUSTER,enabledTransports: ['ws','xhr_streaming'],disabledTransports: ['xhr_streaming']});
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:
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:
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:
constchannel=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:
Like private channels, encrypted channels have their own namespace, 'private-encrypted-'. For more information about encrypted channels, please see the docs.
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:
请发表评论