Implement push notification in pwa when new version available using angular service worker

 

In this article, we will be discussing what a service worker is and how you can update your Progressive Web App (PWA) to the latest version using service worker.

A service worker is a script that runs in the background of your web browser and provides caching capabilities so that your PWA can work offline or in low-quality network conditions.

When a new version of your PWA is available, the service worker will automatically update the cached files and notify the user.

Learning objectives

  • What is service worker
  • Benefits of service worker
  • Install service worker in angular
  • Check for app update using swUpdate service
  • Handle unrecoverable state of app
  • Summary

What is service worker

A service worker is a type of web worker. It runs in the background, separate from your web page. Service worker can intercept network requests, access the browser's cache, and generate notifications.

They can also do other things that don't directly affect the user, like Pre-caching assets.


Service worker are a key component of Progressive Web Apps (PWAs). PWAs are web applications that use modern features to give users a app-like experience.

Benefits of service worker

Service worker are scripts that run in the background of an Angular application. They are used to cache resources and improve the performance of an application. Service workers can also be used to create offline applications. 

Service worker are a type of web worker. Web workers are JavaScript programs that run in the background, separate from the main thread, and don't have access to the DOM. 

Service worker provide many benefits over traditional web applications. They allow for offline caching, which means that resources can be cached on the client's device and accessed even when there is no internet connection.

This is a huge benefit for users with poor or intermittent internet connections. 

Service worker also allow for background processing, meaning that they can perform tasks even when the app is not open. This can free up resources on the main thread and improve overall performance.

Some basic advantages of service worker

  • To improve the performance and provide offline content, a cache network can be used.
  • Push notification, callbacks that allow push notifications to be used can be handled by a service worker.
  • Background sync, Keep the input when offline and synchronize it once it will be online.

Install service worker in angular

To add the Angular service worker to your project by using angular CLI, use the command ng add @angular pwa.    


It configures your project to work with service worker by adding the @angular service-worker package and establishing the necessary files.

After installing angular pwa , You could see the service worker sets to true in angular.json
"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      },
      "serviceWorker": true
    }
  ]

The serviceWorker flag: what does it do?

This flag will cause the production build to include a folder with several files in its output dist folder. The Angular Service Worker file ngsw-worker.js, the runtime configuration of the Angular Service Worker ngsw.json.

Using the ServiceWorkerModule

The ServiceWorkerModule.register() method takes a path to the service worker script as its first argument and an options object as its second argument.

The options object can contain various configuration options for the service worker, such as which scopes it should control.

Once the service worker is registered, it will start controlling any pages that are in its scope and listen for events such as fetch and push. When one of these events occurs, the service worker can choose to respond to it or ignore it.

Check for app update using swUpdate service

It's now easier than ever to keep your Angular apps up-to-date, thanks to the swUpdate service. With a few simple steps, you can configure your app to check for updates and install them automatically.

First we will discuss what is swUpdate service in service worker how you can take advantage of this service in angular application.

When building a progressive web app (PWA), you may want to consider using the swUpdate service worker. This service worker can help ensure that your app is always up-to-date, even if the user is offline.



The swUpdate service worker checks for updates to your app every time it starts up. If an update is available, it will download the new version of your app in the background. Once the download is complete, the new version of your app will be installed and ready to use the next time the user launches it.

If you're using Angular, there's an easy way to integrate swUpdate into your project. The Angular team has created a library that makes it simple to get started with this service worker.

export class UpdateService {

  constructor(public updates: SwUpdate, public dialog: MatDialog) {
    this.updates.available.subscribe(event => {
    	this.checkForUpdates();
    });
  }

  public checkForUpdates(): void {
    this.updates.available.subscribe(event => {
    const dialogRef = this.dialog.open(AskForUpdateComponent, {
        width: '700px',
        data: { tite: 'Confirmation ' },
      });
      dialogRef.afterClosed().subscribe((result: any) => {
        if (result && this.updates.isEnabled) {
         this.updateApp();
        }
      });
    });
  }

  private updateApp(): void {
    console.log('updating to new version');
    this.updates.activateUpdate().then(() => document.location.reload()); 
  }
 }
  
  
Setup a dialog to show to user that the update is available. I am using material dialog here you can have the code.



<div class="modal-header">    
    <h4 class="modal-title" id="modal-basic-title"> Confirmation</h4> 
</div>     
<div class="modal-body">  
    <p>A new version available, please update before continuing, update now ?</p>     
</div>    
<div class="modal-footer"> 
    <button type="button" class="btn btn-outline-dark" (click)="onYesClick()"> Yes, Update</button>   
    <button type="button" class="btn btn-outline-dark" (click)="onNoClick()"> Cancel</button>     
</div> 

Handle unrecoverable state of app


Swupdate is a great tool for managing updates to your angular application, but what do you do when it gets into an unrecoverable state?

For some reasons , sometimes the service worker that is served to the client get broken and there is some steps you can take and show a proper message to user.

@Injectable()
export class HandleUnrecoverableStateService {
  constructor(updates: SwUpdate) {
    updates.unrecoverable.subscribe(event => {
      this.notifyUser(
        'An error occurred that we cannot recover from:\n' +
        event.reason +
        '\n\nPlease reload the page.'
      );
    });
  }

  notifyUser(message: string) {
    console.log(message);
  }
}

Summary

Push notifications in pwa can be extremely useful for keeping users up to date on new content or versions of your app. 

However, implementation can be tricky and should be done carefully to avoid annoying users.

With the angular service worker, push notifications can be easily implemented and customized to fit your needs.


In conclusion,it is necessary to implement push notification in pwa when new version available using angular service worker. This will ensure that users are notified of new content and can access it immediately. Furthermore, it will help to keep the pwa updated and improve user engagement.

Post a Comment

0 Comments