loading...
Cover image for Follow-up: Web Push Notifications And PWA In 2020

Follow-up: Web Push Notifications And PWA In 2020

daviddalbusco profile image David Dal Busco Originally published at Medium ・3 min read

One Trick A Day (35 Part Series)

1) How To Call The Service Worker From The Web App Context 2) Replace Environment Variables In Your Index.html 3 ... 33 3) Inject JavaScript Or CSS At Runtime And On Demand 4) Sometimes You Just Need A Dumb Library 5) Internationalization with Gatsby 6) How To Declare And Use Ionic Modals With Stencil 7) Get App Name And Version In Angular 8) Deploy Apps And Functions To Firebase From A Mono Repo With GitHub Actions 9) Starting In A New Company? Think Npmrc And Git Name 10) Test Angular Pipes With Services 11) Gatsby Tricks: Viewport, CSS Modules Transition And i18n Tricks 12) Takeover The Cordova Facebook Plugin Maintenance 13) Protect Your HTTP Firebase Cloud Functions 14) Create A Menu For Your Gatsby Website Without Libs 15) Create A Modal For Your Angular App Without Libs 16) Add A Slider To You Angular App 17) Test Angular Components and Services With HTTP Mocks 18) Merge Two Objects And Array To Object In JavaScript 19) JSX For Angular Developers 20) More JSX For Angular Developers 21) Create Your Own NPM Cli 22) Third Party Service Providers. Be transparent to each other! 23) React And Web Workers 24) Angular Testing: Mock Private Functions 25) React, Web Workers and IndexedDB 26) React, Web Workers, IndexedDB and ExcelJS 27) GitHub Actions: Hide And Set Angular Environment Variables 28) JavaScript Useful Functions 29) Deeplinking in Ionic Apps With Branch.io 30) Follow-up: Web Push Notifications And PWA In 2020 31) Angular And Web Workers 32) Git Commands I Always Forget 33) An Open Source Medium Like WYSIWYG Editor 34) Currency Picker And Formatter With Ionic React 35) Develop A Konami Code For Any Apps With Stencil

I share one trick a day until the original scheduled date of the end of the COVID-19 quarantine in Switzerland, April 19th 2020. Five days left until this first milestone. Hopefully better days are ahead.


If you follow me on Twitter, you may have read that an application I developed and recently submitted to the stores have been rejected by both Apple and Google because it was not aligned, according them, with their restrictive policy regarding the current COVID-19 pandemic.

I am not writing these lines to share my opinion on these companies, but to share a follow-up to my one year old tutorial: Web Push Notifications in Progressive Web Apps.

Indeed one core concept of the app which was rejected relies on Push Notifications. As it is developed with Ionic and Angular, we are able to unleash a Progressive Web Apps, but is such feature yet well supported?


Introduction

I am writing this article Tuesday 14th April 2020, that’s why it reflects the status of that specific date. If you would read this in the future and notice improvements or changes, ping me!

This afternoon I ran my tests on my Android phone, a OnePlus 6 running Android v10 and on my iPhone 6s running iOS 13.


Android

It works like a charm, period. I tested Web Push Notifications with my phone in idle mode, awake and with the application open. In all cases, I received the notifications. Great work Google 👍.


iOS

Web Push Notifications are still not supported on iOS. The status didn’t change since I published my tutorial in February 2019. As you can notice with the help of Caniuse, the Notifications API is not yet implemented by iOS Safari.


Setup

The Firebase Cloud Messaging set up I displayed in my previous article still remains valid. Of course maybe some screenshots have changed or have been actualized, but the idea remains the same. Moreover, I have set up the tokens for my application in the exact same way and everything went fine.

An interesting thing to notice though, it the comment from Galilo Galilo. According his/her experience, the Firebase dependencies used in the service worker had to be set as the exact same version number as the one used in package.json . I did not had this problem but it is something which might be worth to keep in mind.


Implementation

To the exception of the following deprecation, which can or not be improved, the implementation displayed in my previous tutorial remains also valid. It is the one I have implemented in our application and therefor the one I successfully tested today on my Android phone.

That being said, I think that there might be an easier way, specially if you are using AngularFire, to implement Web Push Notifications in a Progressive Web Apps. I did not check it out but before following my tutorial it maybe deserves a quick research, just in case you would be able to spare some time 😉.


Deprecation

Not a big deal but while having a look at the code I noticed that await messaging.requestPermission(); was marked as deprecated. It can be updated as following:

if (Notification.permission !== 'denied') {
    await Notification.requestPermission();
}

Altogether

Altogether, my enhanced Angular service which takes care of registering the Web Push Notifications and requesting the permissions.

import {Injectable} from '@angular/core';

import {firebase} from '@firebase/app';
import '@firebase/messaging';

import {environment} from '../../../environments/environment';

@Injectable({
    providedIn: 'root'
})
export class FirebaseNotificationsPwaService {

    async init() {
        navigator.serviceWorker.ready.then((registration) => {
            if (!firebase.messaging.isSupported()) {
                return;
            }

            const messaging = firebase.messaging();

            messaging.useServiceWorker(registration);

             messaging
                 .usePublicVapidKey(environment.firebase.vapidKey);

            messaging.onMessage((payload) => {
                // If we want to display 
                // a msg when the app is in foreground
                console.log(payload);
            });

            // Handle token refresh
            messaging.onTokenRefresh(() => {
                messaging.getToken().then(
                    (refreshedToken: string) => {
                    console.log(refreshedToken);
                }).catch((err) => {
                    console.error(err);
                });
            });
        }, (err) => {
            console.error(err);
        });
    }

    async requestPermission() {
        if (!Notification) {
            return;
        }

        if (!firebase.messaging.isSupported()) {
            return;
        }

        try {
            const messaging = firebase.messaging();

            if (Notification.permission !== 'denied') {
                await Notification.requestPermission();
            }

            const token: string = await messaging.getToken();

            // User token
            console.log(token);
        } catch (err) {
            console.error(err);
        }
    }
}

Summary

Hopefully one day we will be able to send Web Push Notifications on iOS devices too 🤞.

Stay home, stay safe!

David

Cover photo by Javier Allegue Barros on Unsplash

One Trick A Day (35 Part Series)

1) How To Call The Service Worker From The Web App Context 2) Replace Environment Variables In Your Index.html 3 ... 33 3) Inject JavaScript Or CSS At Runtime And On Demand 4) Sometimes You Just Need A Dumb Library 5) Internationalization with Gatsby 6) How To Declare And Use Ionic Modals With Stencil 7) Get App Name And Version In Angular 8) Deploy Apps And Functions To Firebase From A Mono Repo With GitHub Actions 9) Starting In A New Company? Think Npmrc And Git Name 10) Test Angular Pipes With Services 11) Gatsby Tricks: Viewport, CSS Modules Transition And i18n Tricks 12) Takeover The Cordova Facebook Plugin Maintenance 13) Protect Your HTTP Firebase Cloud Functions 14) Create A Menu For Your Gatsby Website Without Libs 15) Create A Modal For Your Angular App Without Libs 16) Add A Slider To You Angular App 17) Test Angular Components and Services With HTTP Mocks 18) Merge Two Objects And Array To Object In JavaScript 19) JSX For Angular Developers 20) More JSX For Angular Developers 21) Create Your Own NPM Cli 22) Third Party Service Providers. Be transparent to each other! 23) React And Web Workers 24) Angular Testing: Mock Private Functions 25) React, Web Workers and IndexedDB 26) React, Web Workers, IndexedDB and ExcelJS 27) GitHub Actions: Hide And Set Angular Environment Variables 28) JavaScript Useful Functions 29) Deeplinking in Ionic Apps With Branch.io 30) Follow-up: Web Push Notifications And PWA In 2020 31) Angular And Web Workers 32) Git Commands I Always Forget 33) An Open Source Medium Like WYSIWYG Editor 34) Currency Picker And Formatter With Ionic React 35) Develop A Konami Code For Any Apps With Stencil

Posted on by:

daviddalbusco profile

David Dal Busco

@daviddalbusco

Creator of DeckDeckGo | Organizer of the Ionic Zürich Meetup

Discussion

markdown guide