A useful feature of service workers is the concept of Network Interception. It can be used to intercept a fetch request and change the response returned. In this exercise we’ll see how it works by coding a simple service worker that intercepts an image request and returns a different fetched response.
Paste in the following code:
self.addEventListener('install', function(e) {
console.log('[ServiceWorker] Install');
});
self.addEventListener('activate', function(event) {
console.log('[ServiceWorker] Activate');
});
self.addEventListener('fetch', function(event) {
console.log('Network intercept example. Testing this URL for a png: ', event.request.url);
if (/\.png$/.test(event.request.url)) {
event.respondWith(
fetch('https://static.boredpanda.com/blog/wp-content/uploads/2017/01/angry-cat-photography-02-5874a28aee900__700.jpg',
{ mode: 'no-cors'}).then(function(response) {
console.log("Response from network intercept " + response);
return response;
})
)}
else return fetch(event.request);
});
This code simply creates handlers for the
install
andactivate
events with logging statements, but then in thefetch
event intercepts a call to load a .png file and instead returns a silly cat pic.
Next you need to register this new service worker so the app is aware of it and can download it. The code checks to make sure the browser supports serviceWorker
and then calls the register
method with the name of the new service worker file. Open your index.html file and add the following into the <head></head>
of the page:
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js')
.then(() => console.log('service worker installed'))
.catch(err => console.log('Error', err));
}
</script>
This is considered a progressive enhancement, where it will only enhance the app with the service worker features where supported but run just fine elsewhere.
Now we need to make sure our app has a .png to load. I left one commented out in the starter app for quick testing. While in index.html file, scroll down to the Pending todos template code and uncomment the following (it’s marked with a comment KEEP FOR NETWORK INTERCEPT LESSON):
<img src="img/logo.png" width="320" height="240">
Now run the application again using phonegap serve
but be sure to first read the following before navigating to it:
Since service workers are required to be run on a secure site (
https://
), OR during dev’t withlocalhost
, we need to open the browser and specifylocalhost
instead of the IP Address returned from theserve
. Note that you still need to include the port in the URL. The default is 3000 unless you’ve specified otherwise, so you would navigate tolocalhost:3000
as shown below.