Part 6: Implement Push Notifications in Your Progressive Web App
Introduction
This guide will help you set up your progressive web app to handle push notifications.
Initialize Firebase
Push notifications in progressive web apps require Firebase to be set up as early as possible. To do so, you need to create a custom index.html and initialize Firebase there:
-
Create a custom
index.htmlin yourtheme\webfolder by following this guide. -
Edit the created
index.htmlfile in your favorite text editor. -
Add below text before the line
<script src="mxclientsystem/mxui/mxui.js?{{cachebust}}"></script>(replacefirebaseConfigwith your configuration from part 3):<script src="https://www.gstatic.com/firebasejs/10.11.0/firebase-app-compat.js"></script> <script src="https://www.gstatic.com/firebasejs/10.11.0/firebase-messaging-compat.js"></script> <script> const firebaseConfig = { apiKey: "...", authDomain: "...", projectId: "...", storageBucket: "...", messagingSenderId: "...", appId: "..." }; firebase.initializeApp(firebaseConfig); </script> -
Create the file
theme\web\firebase-messaging-sw.jswith the following content (replacefirebaseConfigwith your configuration from part 3):importScripts('https://www.gstatic.com/firebasejs/10.11.0/firebase-app-compat.js'); importScripts('https://www.gstatic.com/firebasejs/10.11.0/firebase-messaging-compat.js'); const firebaseConfig = { apiKey: "...", authDomain: "...", projectId: "...", storageBucket: "...", messagingSenderId: "...", appId: "..." }; firebase.initializeApp(firebaseConfig); const messaging = firebase.messaging(); -
Back in Studio Pro, set the constant
WebPushVapidKeyfound in_USE ME/Web/in the Push Notifications module to the public key of the Web Push certificate you created in part 3.
-
Add the snippet
WebRegistration_Snippetfound in_USE ME/Webin the Push Notifications module to your home page. It contains a button that your users must click to register for push notifications. -
Stop the Mendix Runtime in Studio Pro if it is running and start it afterwards. Do not use Rerun, as that will not pick up the changes in your theme folder.
You have now successfully added a button to enable receiving push notifications for your users. Go ahead to the next section to test sending a push notification.