12

it seems that angular6 does not support background syncing with service worker. What are the steps required to do this without any library in an angular service?

https://developers.google.com/web/updates/2015/12/background-sync

How and where can I access WorkerGlobalScope in an angular6 application directly so that background sync can be done.:

self.addEventListener('sync', function(event) {
  if (event.tag == 'myFirstSync') {
    event.waitUntil(doSomeStuff());
  }
});

The problem is that the angular CLI generates the servicworker file (ngsw-worker.js). Is there a way to inject / modify / extend this file? Yes, i can edit the file ngsw-worker.js by hand or with another fancy trick. Is there an official way to do this?

yonexbat
  • 2,902
  • 2
  • 32
  • 43
  • 1
    I also had the idea to add two serviceworkers, but this seems not to work https://gist.github.com/bahmutov/36b4b6e8f17b1edd69484a271b7c8634 – yonexbat Jul 22 '18 at 04:53
  • 2
    Salü. Looks like they haven't implemented it yet in ngsw-worker.js :-( As an alternative you can use workbox as a Service Worker Library. See https://developers.google.com/web/tools/workbox/modules/workbox-background-sync – Stef Chäser Jul 24 '18 at 11:10
  • 1
    @yonexbat **Please try this its working with using some customization code** https://golb.hplar.ch/2018/12/background-sync-ng.html – Pradip Asodariya Dec 11 '18 at 07:46

1 Answers1

8

Yes you can use your custom script to extend the capabilities of Angular's service worker.

Just follow below steps:

  1. Create a js file with your custom script let's say sw-custom.js under src directory of your project.
  2. Add "importScripts('./ngsw-worker.js')" at top of sw-custom.js file.
  3. Add sw-custom.js file to angular.json file under scripts section.
  4. Now register your sw-custom.js file in app module instead of

ngsw-worker.js

That's it now you can write your script here as per your need.

Maybe it is not correct approach but it works.

Here is the blog for same.

Piyush
  • 589
  • 4
  • 11
  • 1
    Tnx. This seems to work. I had to register the script sw-custom.js in angular.json, so it will be copied to the dist folder. – yonexbat Feb 20 '19 at 21:49
  • Blog on Wayback Machine: https://web.archive.org/web/20190103022602/http://jakubcodes.pl/2018/06/13/enhancing-angular-ngsw/ – Mark Rendle Jul 16 '19 at 10:11