Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to edit your service worker file for an Angular CLI project

I have added the @angular/pwa package to my Angular CLI project with the command ng add @angular/pwa --project *project-name* so it becomes a progressive web applicaiton, and this adds a service worker I know. I want to edit that default service worker to support e.g. handling Shared Targets links. I see that the service worker is registered to a file calleded ngsw-worker.js using the "Inspect" option in Google Chrome. How can I edit that service worker (ngsw-worker.js) created by the Angular CLI when compiled with ng build --prod? What is the best way?

like image 651
ravo10 Avatar asked Oct 16 '19 13:10

ravo10


People also ask

Which command is used to configure service worker?

Adding a service worker to your projectlink To set up the Angular service worker in your project, use the CLI command ng add @angular/pwa . It takes care of configuring your application to use service workers by adding the @angular/service-worker package along with setting up the necessary support files.

How do you by pass the service worker for a particular request Angular?

To bypass the service worker, set ngsw-bypass as a request header, or as a query parameter. The value of the header or query parameter is ignored and can be empty or omitted.

What is NGSW config JSON?

The ngsw-config.json configuration file specifies which files and data URLs the Angular service worker should cache and how it should update the cached files and data. The Angular CLI processes the configuration file during ng build .

What is Serviceworker in Angular?

At its simplest, a service worker is a script that runs in the web browser and manages caching for an application. Service workers function as a network proxy. They intercept all outgoing HTTP requests made by the application and can choose how to respond to them.


1 Answers

This is a good question, don't know way it's so downvoted. As explained here the best way to accomplish this is to extends the original service worker with your own:

importScripts('./ngsw-worker.js');

// my new features
self.addEventListener('notificationclick', (event) => {
  console.log('notification clicked!')
});

then add the new one to angular.json assets array:

"assets": {
  ...,
  "src/my-service-worker.js"
}

then replace the sw file in app.module:

//app.module.ts
ServiceWorkerModule.register('my-service-worker.js', { enabled: environment.production 
})

Clean and easy.

like image 166
Nemus Avatar answered Sep 28 '22 15:09

Nemus