Skip to content

Instantly share code, notes, and snippets.

@unr
Created September 22, 2019 23:48
Show Gist options
  • Select an option

  • Save unr/1910b603ec5d9e228bed04a57c7cd88e to your computer and use it in GitHub Desktop.

Select an option

Save unr/1910b603ec5d9e228bed04a57c7cd88e to your computer and use it in GitHub Desktop.

Revisions

  1. unr created this gist Sep 22, 2019.
    37 changes: 37 additions & 0 deletions pusher.client.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    // plugins/pusher.client.js
    // Browser only, create a new instance of pusher on load
    // Accessible via this.$pusher

    import Pusher from 'pusher-js';

    export default ({ env, store }, inject) => {
    // we need withCredentials for our CORS setup
    Pusher.Runtime.createXHR = () => {
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    return xhr;
    };
    const pusher = new Pusher(env.pusherAppKey, {
    cluster: env.pusherCluster,
    encrypted: true,
    // Laravel Echo basically just set up this endpoint
    authEndpoint: `${env.apiUrl}broadcasting/auth`
    });

    // Pass a channel ID to leave it
    const leaveChannel = channelName => {
    const channel = pusher.channel(channelName);
    if (channel) channel.unsubscribe();
    };

    // You can connect to default channels here
    pusher.subscribe('default').bind('someEvent', notification => {
    store.commit('handleSomeEvent', notification);
    });

    // Now accessible in views/vuex
    // So you can call this.$pusher from anywhere
    // You can also dynamically call $leaveChannel if needed
    inject('pusher', pusher);
    inject('leaveChannel', leaveChannel);
    };