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?
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.
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With