This example project accompanies our Set up web push notifications with Firebase Cloud Messaging tutorial.
To run this example project, you need:
- The Firebase CLI
- A TalkJS account
- Clone or download this project.
- In the root directory of the project, run:
if you are not already logged in, and log in to your account
firebase login
- Set up Firebase hosting:
Select to either use an existing Firebase project or create a new one. If you create a new one, or you haven't yet set up Firebase Cloud Messaging in the TalkJS dashboard, see Configure Firebase Cloud Messaging in our docs.
firebase init hosting
- Answer the prompted questions:
- Select to use the default (
public
) as your public directory - Select Yes for "Configure as a single-page app?"
- Choose whether to set up automatic builds and deploys with GitHub
- Select No for "File public/index.html already exists. Overwrite?"
- Select to use the default (
- Once initialization is complete, open the Firebase console and select your project.
- On the Project Overview page, click the + icon to add a new app. For the platform, select Web.
- Pick a name for your app.
- After registering the app name, you will see some code samples for adding the Firebase SDK. Copy the
firebaseConfig
JavaScript object. It will look something like this:{ "apiKey": "<FIREBASE_API_KEY>", "authDomain": "<FIREBASE_APP_NAME>.firebaseapp.com", "projectId": "<FIREBASE_APP_NAME>", "storageBucket": "<FIREBASE_APP_NAME>.firebasestorage.app", "messagingSenderId": "<SENDER_ID>", "appId": "<FIREBASE_APP_ID>" }
- Inside
public/index.html
(lines 168-175) andpublic/firebase-messaging-sw.js
(lines 9-16), replace the placeholder object with yourfirebaseConfig
object. - In the Firebase console, click the gear icon and go to Project Settings. In the Cloud Messaging tab, go to the Web configuration section and then click Generate Key Pair.
- Copy the value under “Key Pair”. This is the public key used to encrypt web push notifications.
- Inside
public/index.html
(line 203), paste the value inside the string as the value forvapidKey
. - Inside
public/index.html
, replace<APP_ID>
with your app ID, which you can find in the Settings tab of the TalkJS dashboard. - In the root directory of the project, run:
This will deploy the website at a URL like
firebase deploy --only hosting
https://<FIREBASE_APP_NAME>.web.app
.
- On the device where you want to receive push notifications, go to
https://<FIREBASE_APP_NAME>.web.app
and click the Request token button. Select to allow push notifications if prompted. - Switch to a different tab with another site (this is so that a notification will trigger when you get a new message).
- Add a new message to the TalkJS
sample_conversation
conversation from the other user,sample_user_alice
. A simple way to do this is to go to the Chat UI tab of the TalkJS dashboard and add a message from the Preview chat UI. - You should now receive a push notification to your device with the message text.