Tuesday, July 31, 2018

Learn Service Worker for application offline access

Why service worker introduced?

In Mobile Applications, features like offline functionality, running background services and push notifications are implemented as part of native mobile devices. This will only available in mobile as inbuilt in functionality. Desktop applications and browser-based applications are not available in builtin. These functionalities in a web application are available using service worker. The web page is normally user-initiated request which is handled by the main thread. 

Service worker is separate thread runs in the background to track network request, cache the data, retrieving it and pushing the message to the browser.
Basically, This workers provides the real-time content or cached content based on the network availability. This provides offline access to the application to make it as a progressive web application.

Service worker features

  • It acts as a proxy server between web applications, browser, and network services.
  • This can access the Page level DOM elements.
  • This makes use of javascript promises  that runs without waiting for a request
  • This runs only on https protocol
  • Service worker is a javascript code that runs in the background without user intervention. 
  • Works on https protocol for security reasons

Lifecycle events

There are various events like register/execution/cache/fetch for providing offline access.
Registration First Services worker need to register. Once service worker is registered, Service worker code is copied to the client, and move to next lifecycle event for installation browser will start this in a background thread.
<script>
  // Register the service worker
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('./service-worker.js').then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }).catch(function(err) {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    });
  } else{
  console.log('Service worker support is not aviable in a browser')}
</script>
This will install service worker and specifics javascript file code This checks if service worker is available in the browser, register service worker code in worker.js once page loads Register() returns promise, will be registered if services worker is not registered. else update it. Service worker script code you have to write the code for installation/activate/fetch events.
self.addEventListener('install', function(e) {
});
self.addEventListener('activate', function(e){
});
self.addEventListener('fetch', function(e){
});
Install Event:- This has code for storing data to storage mechanism and allows to save assets for offline access. Activate Event: this will get notified once service worker installation is completed. write a code for removing the older version of caches Fetch Event: This will be called for any resource of service worker to fetch resources like calling ajax API calls.
Service worker API provides fetch -retrieve the content from the cache and
Cache - storing application-specific data to the storage mechanism

script example for offline access:-

 This is a sample code of the angular application for offline access
var dataCacheName = 'mycache-v1';
var cacheName = 'mycache-1';
var filesToCache = [
    '/',
    '/index.html'
];
console.log('ServiceWorker Start');
self.addEventListener('install', function(e) {
    console.log('[ServiceWorker] Install');
    e.waitUntil(
        caches.open(cacheName).then(function(cache) {
            console.log('[ServiceWorker] Caching app shell');
            return cache.addAll(filesToCache);
        })
    );
});

self.addEventListener('activate', function(e) {
    console.log('[ServiceWorker] Activate');
    e.waitUntil(
        caches.keys().then(function(keyList) {
            return Promise.all(keyList.map(function(key) {
                if (key !== cacheName && key !== dataCacheName) {
                    console.log('[ServiceWorker] Removing old cache', key);
                    return caches.delete(key);
                }
            }));
        })
    );
    return self.clients.claim();
});

self.addEventListener('fetch', function(e) {
    console.log('[Service Worker] Fetch', e.request.url);
    e.respondWith(
        caches.match(e.request).then(function(response) {
            return response || fetch(e.request);
        })
    );
});
console.log('ServiceWorker End');
You can check service worker status in chrome using URL chrome://serviceworker-internals. You can see debugging Service worker data in chrome as per below screenshot. service worker debugging chrome

Browser support

Supported by Chrome, Firefox, and Opera. Microsoft Edge has recently introduced supporting this. Apple Safari has plans to support this in the future.
Service workers by default enabled in browsers. You can also check settings in different browsers as follows

Firefox Browser
Open about:config in URL in Firefox, Check dom.serviceWorkers.enabled value, if it is false, change it to true.

Chrome Browser
Open chrome://flags in URL in chrome, Check experimental-web-platform-features value, if it is disabled, Enabled it.

Opera Browser
Open Opera://flags in URL in opera, Check Support for ServiceWorker value, if it is false, change it true.

Microsoft Edge Browser
Open about:flags in url in Edge, Check Enable service workers value, if it is not checked, Checked it.

Once you made changes, Please restart the browser.

Browser tools

These tools are very helpful for a developer for debugging scripts.
Chrome developer tools have the following things
chrome://inspect/#service-workers  - current service worker and storage device information
chrome://serviceworker-internals - this allows to start/stop/debug the services works

Firefox has the following developer tools
about: debugging - This shows a list of registered services workers, You can disable/remove from here

Use cases:-

Offline application access where network bandwidth is limited
Push notifications
GPS support in future

Fix for DOMException: Failed to register a ServiceWorker

During testing service worker code, you used to get this below errors.
Uncaught (in promise) DOMException: Failed to register a ServiceWorker: 

this is an issue with javascript code located in the js file. To debug further on this
go to chrome://serviceworker-internals and open developer tools pages, Debug the worked script file code to see where exactly issue is coming by inspecting it.


Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.

Usually, main HTML page like index.html has service worker code to register it. You get this error in this page only. Here you are configuring javascript file.

Please make sure that you are referring to exact path of the service worker file. or place both files on the same directory.


EmoticonEmoticon

Note: Only a member of this blog may post a comment.