Repository navigation
Introduction to Push Notifications
Push notifications are something we normally think about with native iOS and Android apps, but they can also be used in web apps with browsers supporting service workers. In this lesson, we are going to use the Firebase Cloud Messaging JS library to send notifications to users in an Angular 4 app.
#manifest.json
We need to add a manifest.json file to our app and register it with the Angular CLI. Push Notifications use the service worker browser extension, which must be registered in this manifest.
Add the following to a new file named manifest.json to the /src directory.
NOTE: Keep in mind the gcm_sender_id is the same for ALL apps in the world, so do not change it.
** { "gcm_sender_id": "103953800507" } **
Then link it in the head of the index.html.
#firebase-messaging-sw.js
Push messaging requires a service worker. This allows your app to detect new messages, even after the app has been closed by the user. Create another file in the src/ directory named firebase-messaging-sw.js. The worker just hangs out in the background with the messaging config waiting to notify a user.
In production, your app must be hosted with SSL, https://yourdomain..., which is enabled by default if you deploy to Firebase hosting
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js');
firebase.initializeApp({ 'messagingSenderId': 'YOUR-SENDER-ID' });
SENDER-ID will be different for every firebase server.
const messaging = firebase.messaging();
#angular-cli.json
Lastly, we need to register these files in angular-cli.json.
"apps": [ { "root": "src", "outDir": "dist", "assets": [ "assets", "favicon.ico", "firebase-messaging-sw.js", // <-- here "manifest.json" // <-- and here ] } ]