0.1.2 • Public • Published


This is a wrapper script and libarary which makes use of the JS polyfill for Server-Sent Events located at and makes it easy to manage several connections to push notification or event sources. This library can also be used inside Web Workers (Dedicated or Shared workers)

File Size

  • 15.2kb (Minified)


  <!DOCTYPE html>
  <html lang="en">
          <meta charest="utf-8">
            <title>BeamzerClient - Example</title>
            <script type="text/javascript" src="/path/to/beamzer-client.min.js"></script> 
       <body class="screen">
          <script type="text/javascript">
        var beam = new BeamzerClient({
                    options:{loggingEnabled:true, interval:4500,crossdomain:true}
               // open a connection with relevant callbacks
               beam.start(function onopenCalback(e){
              }, function onerrorCalback(e){ 
               if (e.readyState == EventSource.CLOSED) {
                     console.log('Event was closed');
              }, function onmessageCalback(e){
               // register an event [update]
               beam.on("update", function(e){ });
               // register another event [noupdate]
               beam.on("noupdate", function(e){ });
               // recreate a connection. 
               // unregister an event [update]
               // close all the connection(s)
               beam.stop(function(e){ });

It is important to note that whenever.

AngularJS UseCase Example

The idea here is to loosely couple communications to beamzer-client in an AngularJS app and

    The idea here is to loosely couple the different controllers to the beamzer-client event stream from the server.
    Instead of having multiple observers for each controller scope listening for incoming streams, we have a single
    mediator object powered by $rootScope for this purpose.
;(function(w, angular){
   var module = angular.module("TheAppServices"); // assumes this module has been defined before
   module.factory("$activityStreamer", [function(){
        // assumes that [$values] is another service defined before that contains the stream URL data 
        var ENDPOINT = '',
            CLIENT = null, 
            started = false;
        return {
            start:function(openCallback, errorCallback, msgCallback){
               CLIENT = new w.BeamzerClient({
                  options:{loggingEnabled:true, interval:4500}
               CLIENT.start(openCallback, errorCallback, msgCallback); 
               started = true;           
            addEvent:function(event, callback){
                CLIENT.on(event, callback);
                return started;
}(this, this.angular));  
;(function(w, angular){
  var module = angular.module("TheAppServices");
  module.factory("$sessionStorage", ['$window', function($window){
      var data = null, keys = {};
      function setData(){
         $ = angular.toJSON(data);
      function clearData(){
        $ = data ? (data = {}) && '' : '';
      function getData(){
        return data || angular.fromJSON($ || '{}');
      data = getData();
      return ('sessionStorage' in $window) ? $window.sessionStorage : {
              keys = {};
              clearData((this.length = 0));
              var _data = getData(); 
              return (key in _data)? _data[key] : null;
            setItem:function(key, value){
              var _data = getData();
              _data[key] = angular.toJSON(value);
              setData(keys[String(++this.length)] = key);
              var _i = String(i);
              return (_i in keys)? keys[i] : null;
              var _data = getData();
              delete _data[key];
              setData(keys[String(--this.length)] = key);
}(this, this.angular));
;(function(w, angular){
     var usebuffer = false, 
     app = angular.module("TheApp", ["TheAppServices"]);
     // we assume here that this ficticious app (TheAppServices) has a '#/feeds' route registered prior['$activityStreamer', 
              '$route', function($activityStreamer, $sessionStorage, $rootScope, $route){
          $rootScope.$on('newStreamerRequest', function(event, data){
                  // assuming -- $scope.$emit('newStreamerRequest', {settings:{url:'...',params:{}}}) -- is called
          $rootScope.$on('removeStreamerEvent', function(event, data){ 
               // assuming -- $scope.$emit('removeStreamerEvent', {eventName:'update'}) -- is called
          $rootScope.$on('$destroy', function(event, data){
                    // if we go off from the app itself, kill it... fast!!
                          $rootScope.$broadcast('allStreamerExit', e); // notify all listening scopes (perhaps...)
          $rootScope.$on('$routeChangeStart', function(event, current, previous){
                // if we move away from a 'feeds' route page, buffer all real-time data in sessionStorage!!
                if(previous.url.indexOf('feeds') > -1){ 
                      useBuffer = true;                    
          $rootScope.$on('$routeChangeSuccess', function(event, current, previous){
                /*$rootScope.title = current.title;*/
                // if we move to a 'feeds' route page, prepare to display real-time data in view
                if(current.url.indexOf('feeds') > -1){ 
                        useBuffer = false;
                              $sessionStorage.setItem('ACTIVITY_STREAM_BUFFER', {});
                              $rootScope.$broadcast('newStreamerSuccess', e); // notify all listening scopes
                            $rootScope.$broadcast('newStreamerFailure', e); // notify all listening scopes
                              setTimeout(streams.bind(null, e), 0);
                        $activityStreamer.addEvent('update', function(e){
                              setTimeout(streams.bind(null, e), 0);
                        $activityStreamer.addEvent('noupdate', function(e){
                            $rootScope.$broadcast('noNewStreamerMessageRecieved', e); // notify all listening scopes
                function streams(e){
                          var _buffer = $sessionStorage.getItem('ACTIVITY_STREAM_BUFFER');
                          var _timestamps;
                                _buffer[String(new Date*1)] = e;
                                // from here, you can trigger a toast notification on the screen perhaps...
                                    _timestamps = Object.keys(_buffers);
                                    // we need to make sure that when all 'buffered' messages are sent
                                    // to all $scopes as and at when they were recieved in buffer mode
                                    _timestamps.sort(function(a, b){
                                        return (- a);
                                    angular.forEach(_timestamps, function(value){
                                        $rootScope.$broadcast('newStreamerMessageRecieved', _buffer[value]);
                                        delete _buffer[value];
                              $rootScope.$broadcast('newStreamerMessageRecieved', e); // notify all listening scopes
                          $sessionStorage.setItem('ACTIVITY_STREAM_BUFFER', _buffer);
}(this, this.angular));
/* controller action */
;(function(w, angular){
    var app = angular.module("TheApp");
    app.controller(['$scope', function($scope){
          $scope.updatesList = [];
          $scope.$on('newStreamerMessageRecieved', function(event, data){
              var payload =; // the event object from the handler has a 'data' property...
              // assuming [payload] variable is an array...
              angular.forEach(payload, function(item){
                   $scope.updateList.push(item); // this updates the view via 'ng-repeat' in the view...
}(this, this.angular));

This is a simple SSE server script written in PHP

 # Simple Implementation of event streams on the server -
 sleep(5); // simulate real prod server activity e.g. database read operation 
 $data = array('status' => 'OK');
 $payload = "id: 5RWF637yh9983az021mn \n";
 $payload .= "event: update \n";
 $payload .= "data: " . json_encode($data) . " \n\n"; // the last line must end with 2 line feed characters
 header('Content-Type: text/event-stream');
 echo $payload;

This is another simple SSE server script written in Node.js (using ssenode)

// Simple Implementation of event streams on the server -
const { Source, EventStream } = require('ssenode');
const uuidv4 = require('uuid/v4');
const exp = require('express');
const app = exp()
const source = new Source(uuidv4);
app.use(EventStream.init(source, { no_id:false }));
app.get('/stream', (req, res) => {
   setTimeout(() => { // simulate real prod server activity e.g. database read operation
        }, null, 'update')
   }, 5000); 

Web Worker example

    const worker = new Worker("./push-notifs.js");
    worker.addEventListener("message", (event) => {
        let data =;
            setTimeout(function() => {
    }, false);
    setTimeout(() => {
    }, 8900);
    // push-notifs.js file
    let globale = self, beam = null;
    addEventListener("message", (event) => {
        if( === true){
            beam = new BeamzerClient({
   => {
            (e) => {
            beam.on("notification", (e) => {
        if( === true){
            if(beam !== null){
                beam.close((e) => {
                    beam = null; // reclaim memory
    }, false);

Helper Hints

While you implement beamzer-client, there are afew things to watch out for.

  1. If users create multiple tabs for your beamzer-enabled web app, they will invariably be creating multiple SSE (EventSource) connection to your server. So, you might want to consider disconnecting from the server, whenever a user minimizes the window where your web app is loaded or switches from the tab where your web app is loaded. Use the page-visiblity JavaScript API or document.hasFocus(). Thankfully, there's this JavaScript Library called Idle.js for watching the users' every move and it's easy to setup and use and i very much recommend it.

  2. Use localStorage "storage" events to update event-source data across all non-active tabs. Watch out for Edge though (you may have to use cookie polling as a fall back) as it lacks support for cross-tab "storage" events. I think it should be fixed by Edge 16+


Available on all major browsers including IE8 - If you discover any bugs, please log an issue for it and i'll surely get look into it. If you wish to provide fallback support for web workers in Old IE (IE 8 / 9). Then you can check out this polyfill library




I welcome all contributions to make this software better. please send an email to communicate your thoughts on imporvements and features.

Package Sidebar


npm i beamzer-client

Weekly Downloads






Unpacked Size

78.2 kB

Total Files


Last publish


  • isocroft