How to implement Service Workers in an AngularJS application for offline experience
Asked Answered
C

0

7

I am trying to implement a service worker in one of my AngularJS apps. Based on the tutorials (mostly MDN), I have come up with the following implementation to merge it with AngularJS.

First, since app.run() seems to be the correct place. I have in my run block the following code:

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('workerFile.js')
  .then(function(reg) {
    console.log('Registration done');
  },function(error) {
    console.log('Registration failed with ' + error);
  });
}

My service worker files is like :

this.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open('v1').then(function(cache) {
      return cache.addAll([
        'index.html'
      ]);
    })
  );
});

and

this.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
  );
});

Having done this, I expect my index.html file to be cached and served offline. But that's not happening yet. While online the file is served each time for the server (seen in fiddler).

I have tried changing this to self in a worker file. That didn't help. Also, I am testing it currently on localhost so I believe it should not have unsafe-browsing issues. I am very new to the concept of Workers in JavaScript, hence do not have enough options to try out.

Can someone point me to my mistake here? Apparently, there aren't many articles on the internet on this.

P.S: I visited this Question: didn't help much.

Update: Having a look again at the docs, I believe it has something to do with the scope property while registering. How should I define this property to include my entire application? I tried using {scope: '/'} and it doesn't seem to work.

Crenelation answered 6/6, 2017 at 10:35 Comment(6)
Thanks @Igor for pointing it out. Added the link nowCrenelation
Any success how we can notify our angular app when service worker receive push or any other event?Mulford
That is done using listeners for postMessage event..since angular and workers work in a different context, you will have to do a $scope.apply() after recieving the dataCrenelation
Can you please share code,it would be really helpful. Thank you.Mulford
` self.addEventListener('push', function(event) { event.postMessage("xyz",event.data.json()); event.waitUntil(self.registration.showNotification(title, options)); }); window.addEventListener('xyz',function(e) { console.log('asdsa000'); });`Mulford
The code is tried, but no success.Mulford

© 2022 - 2024 — McMap. All rights reserved.