We’ve released JSONp support for Pusher‘s Javascript client.

JSONp is a way of making cross-domain GET requests from the browser. The Pusher client uses it (optionally) to ask your app for channel authentication when using private and presence channels.

The library still uses Ajax under the hood by default and that works perfectly well when your authentication end-point lives in the same domain as the HTML pages using Pusher. The alternative JSONp authentication is useful for when you want a separate service to act as an authentication provider. Think embeddable widgets.

To use JSONp support, you must use Pusher’s client version 1.6 or above.

Switching to JSONp support is easy. You have to tell Pusher where to find your end-point and switch the default Ajax transport to ‘jsonp’:

<script src="http://js.pusherapp.com/1.6/pusher.min.js"></script><script>// <![CDATA[
Pusher.channel_auth_endpoint = 'http://myserver.com/pusher_jsonp_auth';
  Pusher.channel_auth_transport = 'jsonp';
// ]]></script>

Then you would subscribe to a private or presence channel, as needed.

<script>// <![CDATA[
var pusher = new Pusher('MY_PUSHER_KEY');
  var channel = pusher.subscribe('private-test_channel');

  channel.bind('greet', function(data) {
// ]]></script>

That’s it for the client side. Now you just need to wrap the server’s authentication response in the function name provided in the query string. This parameter is aptly named ‘callback’ and Pusher.js sends it automatically to your JSONp end-point. This is because JSONp works by requiring a remote script that executes a function defined in your local page (Pusher.js defines that function for you).

This is a Rails example of how that end-point would look like.

auth = Pusher['private-test_channel'].authenticate(params[:socket_id], {
  :user_id => current_user.id,
  :user_info => {:name => current_user.name}
render :text => params[:callback] + "(" + auth.to_json + ")"

That’s it. Happy pushing!

P.s. Have you built realtime apps with Pusher? If not, go on, create a free Pusher account and let us know what you think. We’d love to hear from you!

About Max Williams

Max is CEO of Pusher, and is passionate about the ways that technology can be used to make life better and more enjoyable for people. He loves using APIs and developer tools, and is obsessed with finding things that can be better done by a machine. His posts tend to be about life at Pusher, and the ways that we experiment with our culture and processes to create awesome things.