pusher / pusher-js Goto Github PK
View Code? Open in Web Editor NEWPusher Javascript library
Home Page: http://pusher.com
License: MIT License
Pusher Javascript library
Home Page: http://pusher.com
License: MIT License
This issue represents problems with the connection to Pusher from the JavaScript library:
state_change
events not being triggered after sleeppusher.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
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?
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'
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...
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?
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?
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.
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>
https://github.com/pusher/pusher-js/blob/master/src/events_dispatcher.js#L67
If index is -1, last callback function will be deleted. So, in this case, if I did, e.g.:
channel.bind("user-updated", func1)
and then
channel.unbind("user-updated", someAnotherFunc)
it will delete func1 callback, which is wrong.
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?
Self-hosting is important because CDN's do fail. Therefore a proper self-hosting solution is very important to any serious use of this library and service.
I have forked this library to try and help improve this, we'll see where it gets to.
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?
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..
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)
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?
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.
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?
I have been working with pusher channels and am stuck with the following problem:
Using presence channels in Pusher (http://pusher.com), I can get notified in the server side when someone connects or disconnects from a presence channel, but how can I get notified when client gets disconnected from the internet?
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).
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; };
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,
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.
It wouldn't be possible to open source the little state machine (+ it's attached event system)? I really like it's petite elegance.
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"}}}
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):
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.
Since the call is a post and auth credentials are being created a 201 is more appropriate.
Many people abuse 200 so you probably need to look for both.
Ideally:
xhr.status == 200 || xhr.status == 201
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.
This has been raised a few times so it would be good to have this added to the EventDispatcher
object:
https://github.com/pusher/pusher-js/blob/master/src/pusher_event_dispatcher.js
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.
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.
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.
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?
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.
As this is generally a bad idea to let foreign data unchecked, I guess this should be addressed. Otherwise the server just gets flooded with pings. Please check this out:
2ff5fd1#commitcomment-4941679
I'm not sure if this behaviour is part of the intended fallback strategy, but it seems a bit odd to me.
If a connection has successfully been made using websockets, why ever use fallbacks? Why not reconnect via websocket after connectivity is regained?
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
The used strategy is always saved to localStorage.pusherTransportUnencrypted
because the CachedStrategy instance does not received the encrypted
config. This value is always undefined and thus validates to unencrypted.
https://github.com/pusher/pusher-js/blob/master/src/strategies/cached_strategy.js#L12
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
There's no parameter checking at the moment:
https://github.com/pusher/pusher-js/blob/master/src/pusher.js#L75
Maybe something like:
subscribe: function(channel_name) {
if( (channel_name instanceof String) === false ) {
throw '"channel_name" must be of type String'
}
// ... other code
}
Similar to the parameter checking work being undertaken on the Pusher
constructor.
Hi, I have the following use case:
This is what I'm doing currently to trigger an event:
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:
/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.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()
}
}
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]
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:
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.
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":{}}
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!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.