index.js

For our app, index.js is the SW script, and it is located in \wittr\public\js\sw\index.js.

Fetch event listener
A fetch event controls requests

self.addEventListener('fetch', function(event) {
  console.log(event.request);
});

To see the output of that code, in the browser navigate to localhost:8888/sw.js

 

indexController.js

The starting point is index.js. However, the main work happens in public/js/main/indexController.js

We want to register the SW as soon as our apps starts up.
So let’s open \wittr\public\js\main\IndexController.js

The constructor sets up the app.

export default function IndexController(container) {
  this._container = container;
  this._postsView = new PostsView(this._container);
  this._toastsView = new ToastsView(this._container);
  this._lostConnectionToast = null;
  this._openSocket();
  this._registerServiceWorker();
}

_openSocket()
Opens a WebSocket connection.

_registerServiceWorker()
Notice that at the end it registers the SW.

A common practice in JavaScript is to start a method with an underscore

if the method will ever be called by other methods of this object (i.e. like a private method)

The implementation of the _registerServiceWorker() function should be as follows:

IndexController.prototype._registerServiceWorker = function() {
  // TODO: register service worker
  if (!navigator.serviceWorker) return;
  
  navigator.serviceWorker.register('/sw.js').then(function(reg) { 
    console.log('Registration worked!');
  }).catch(function(err) {
    console.log('Registration failed!');
  });
}; 

HTTPS Only

Service Workers only work on HTTPS to prevent evil people from taking over it and eventually control the content you’ll be receiving.