Book Image

Service Worker Development Cookbook

By : Sean Amarasinghe
Book Image

Service Worker Development Cookbook

By: Sean Amarasinghe

Overview of this book

It would be nice to have web apps that work offline and send push notifications. This is now possible with Service Workers, which can add native-like functionality to your web apps without requiring a download. This book will get your mobile and web apps functioning without Internet connectivity, improve performance and network interaction in order to increase the level of availability, and show you how to build performant applications that seamlessly integrate with third-party APIs. We’ll show you how to add Service Worker functionality to web apps and sites, access offline content through basic and advanced techniques, and build powerful interactive system notifications. We’ll also teach you about cache functionality and assets to provide immediate load even over narrow connections. We conclude by giving you various tips to improve app performance, including the background sync technique. By the end of this book, you’ll know build high performing and faster web and mobile applications with Service Workers.
Table of Contents (17 chapters)
Service Worker Development Cookbook
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Creating mock responses


In order to mock API responses from your server to your app, which is instead of actual API responses for the API requests, we can make the service worker return mock responses that will be identical to an API response.

Getting ready

To get started with service workers, you will need to have the service worker experiment feature turned on in your browser settings. If you have not done this yet, refer to the previous recipe: Setting up service workers. Service workers only run across HTTPS. To find out how to set up a development environment to support this feature, refer to the following recipes: Setting up GitHub pages for SSL, Setting up SSL for Windows, and Setting up SSL for Mac.

How to do it...

Follow these instructions to set up your file structure (these can also be found in the provided directory, 01/03):

  1. First, we need to create an index.html file as follows:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Detailed Registration</title>
    </head>
    <body>
      <p>Network status: <strong id="status"></strong></p>
      <div id="request" style="display: none">
        <input id="long-url" value="https://www.packtpub.com/" size="50">
          <input type="button" id="url-shorten-btn" value="Shorten URL" />
        </div>
        <div>
          <input type="checkbox" id="mock-checkbox" checked>Mock Response</input>
        </div>
        <div>
          <br />
          <a href="" id="short-url"></a>
        </div>
      </div>
    
      <script>
        function printStatus(status) {
          document.getElementById('status').innerHTML = status;
        }
    
        function showRequest() {
          document.getElementById('url-shorten-btn')
          .addEventListener('click', sendRequest);
          document.getElementById('request').style.display = 'block';
        }
    
        function sendRequest() {
          var xhr = new XMLHttpRequest(),
            request;
    
                xhr.open('POST',
                'https://www.googleapis.com/urlshortener/v1/url?' +
                'key=[Your API Key]');
          xhr.setRequestHeader('Content-Type', 'application/json');
    
          if (document.getElementById('mock-checkbox').checked) {
                    xhr.setRequestHeader('X-Mock-Response', 'yes');
          }
    
          xhr.addEventListener('load', function() {
            var response = JSON.parse(xhr.response);
            var el = document.getElementById('short-url');
    
            el.href = response.id;
            el.innerHTML = response.id;
          });
    
          request = {
            longUrl: document.getElementById('long-url').value
          };
    
          xhr.send(JSON.stringify(request));
        }
    
        if ('serviceWorker' in navigator) {
    
          navigator.serviceWorker.register(
            'service-worker.js',
            { scope: './' }
          ).then( function(registration) {
            if (navigator.serviceWorker.controller) {
                printStatus('The service worker is currently handling ' + 
                'network operations.');
                showRequest();
            } else {
                printStatus('Please reload this page to allow the ' + 'service worker to handle network operations.');
                  }
          }).catch(function(error) {
            document.getElementById('status').innerHTML = error;
          });
        } else {
                   document.getElementById('status').innerHTML = 'unavailable';
              }
      </script>
    </body>
    </html>
  2. Create a JavaScript file called service-worker.js in the same folder as the index.html file with the following code:

    self.addEventListener('fetch', function(event) {
      console.log('Handling fetch event for', event.request.url);
      var requestUrl = new URL(event.request.url);
    
      if (requestUrl.pathname === '/urlshortener/v1/url' &&
          event.request.headers.has('X-Mock-Response')) {
    
        var response = {
          body: {
            kind: 'urlshortener#url',
            id: 'http://goo.gl/IKyjuU',
            longUrl: 'https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html'
          },
          init: {
            status: 200,
            statusText: 'OK',
            headers: {
              'Content-Type': 'application/json',
              'X-Mock-Response': 'yes'
            }
          }
        };
    
        var mockResponse = new Response(JSON.stringify(response.body),  
            response.init);
    
        console.log('Responding with a mock response body:', 
            response.body);
        event.respondWith(mockResponse);
      }
    });
  3. With your two files in place, you can navigate to the GitHub page, https://username.github.io/service-workers/01/03/index.html, and you will see the success message in your browser.

How it works...

After the service worker registers itself successfully, we check to make sure that it is currently handling the network operations:

if (navigator.serviceWorker.controller) {
printStatus('The service worker is currently handling 
network operations.');
…
}

In this case, we are calling the showRequest() function to add an event listener to the URL shorten button, and show the request block. Otherwise, the whole request block will be hidden:

function showRequest() {
   document.getElementById('url-shorten-btn')
.addEventListener('click', sendRequest);
   document.getElementById('request').style.display = 'block';
}

The sendRequest() function builds the HTTP request. It creates a POST request with a URL of the Google API for URL shortening:

xhr.open('POST',
        'https://www.googleapis.com/urlshortener/v1/url?' +
  'key=[Your API Key]');

You will have to obtain an API key for this service to be used. For this, follow these instructions:

  1. Visit the Google Developers Console page at https://console.developers.google.com.

  2. You can either select an existing project or create a new one.

  3. Expand APIs & auth, in the sidebar on the left.

  4. Click APIs. Now, in the list of APIs provided, make sure the status is ON for the Google URL Shortener API.

  5. Finally, in the sidebar on the left-hand side, select Credentials.

If the Mock Response is checked, set the request header X-Mock-Response to yes:

if (document.getElementById('mock-checkbox').checked) {
      xhr.setRequestHeader('X-Mock-Response', 'yes');
    }

Now add an event listener to the load event and pass in a callback to assign the response data to the link displaying the result:

xhr.addEventListener('load', function() {
var response = JSON.parse(xhr.response);
var el = document.getElementById('short-url');

   el.href = response.id;
   el.innerHTML = response.id;
});

At the end of the sendRequest function, we are sending the original URL as well as the request object we built as a request:

request = {
        longUrl: document.getElementById('long-url').value
      };
xhr.send(JSON.stringify(request));

In the service-worker.js file, we are adding an event listener for the fetch event. We check that the request URL path has the urlshortner in it and the request header has X-Mock-Response:

if (requestUrl.pathname === '/urlshortener/v1/url' &&
    event.request.headers.has('X-Mock-Response')) {
…
   }

We build a mock response object with a body, status, and the headers:

   var response = {
      body: {
        kind: 'urlshortener#url',
        id: 'https://goo.gl/KqR3lJ',
        longUrl: 'https://www.packtpub.com/books/info/packt/about'
      },
      init: {
        status: 200,
        statusText: 'OK',
        headers: {
          'Content-Type': 'application/json',
          'X-Mock-Response': 'yes'
        }
      }
    };

Finally, we create a response with the mock response:

var mockResponse = new Response(
JSON.stringify(response.body), response.init);

console.log('Mock Response: ', response.body);
event.respondWith(mockResponse);