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.
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.
Follow these instructions to set up your file structure (these can also be found in the provided directory, 01/03
):
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>
Create a JavaScript file called
service-worker.js
in the same folder as theindex.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); } });
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.
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:
Visit the Google Developers Console page at https://console.developers.google.com.
You can either select an existing project or create a new one.
Expand APIs & auth, in the sidebar on the left.
Click APIs. Now, in the list of APIs provided, make sure the status is ON for the Google URL Shortener API.
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);