admin管理员组

文章数量:1244304

I want to set up Firebase cloud messaging for my website. My website runs on HTML and vanilla Javascript and Nodejs for the backend. I have read the docs and still find it difficult. Also, most of the answers on stack overflow are outdated on the Firebase version.

This is what I do not understand:

Client side

  • How do I get the Firebase config?
  • What is firebase-messaging-sw.js and where do I put it?
  • How do I get user permission?
  • How do I get the FCM Token?
  • How do I set up the messaging.onMessage() function?
  • How do I receive background messages?

Server Side

  • Where do I put the Firebase config settings?
  • How do I send a message?

I want to set up Firebase cloud messaging for my website. My website runs on HTML and vanilla Javascript and Nodejs for the backend. I have read the docs and still find it difficult. Also, most of the answers on stack overflow are outdated on the Firebase version.

This is what I do not understand:

Client side

  • How do I get the Firebase config?
  • What is firebase-messaging-sw.js and where do I put it?
  • How do I get user permission?
  • How do I get the FCM Token?
  • How do I set up the messaging.onMessage() function?
  • How do I receive background messages?

Server Side

  • Where do I put the Firebase config settings?
  • How do I send a message?
Share Improve this question asked Jul 12, 2023 at 2:17 Etemire EwomaEtemire Ewoma 4325 silver badges13 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 14

How to set up Firebase Cloud Messaging (FCM) Javascript, HTML, Node JS

Client Side

To set up Firebase using the above tools is not as simple as I thought. So first of all we will start with the client-side setup.

These are the steps I used in getting my set-up ready.

  1. Read the Firebase Docs Here.
  2. Get the Firebase CDN
  3. Get the App Key (From firebase Console)
  4. Get the Firebase config (From firebase Console)
  5. Set up Firebase for notification
  6. Set up Firebase to receive background notification

1. Read the Firebase Docs Here.

You have to read this just because I can't really cover everything.

2. Get the Firebase CDN

So you will need to get the latest Firebase CDN, for me, I used v10.0.0.

<script src="https://cdnjs.cloudflare./ajax/libs/firebase/10.0.0/firebase-app-pat.min.js" integrity="sha512-QxCI6n9lTLJpOHQcpZV2klXd5DhqSrGGe1rU2Cbr9+uCTNozkfbs/w5LVrk/pIgJwd1sFaKtvWGqw3EBtguHcA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/firebase/10.0.0/firebase-messaging-pat.min.js" integrity="sha512-S1ikyG/9rWv+KJjbwHJGTKeYYnmVJxcvgQOBztLUPsRY4ZoSmPK+b8jTiDrt4lSP5SlpkpEQCbhwWQJK+kx7jQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Note that the cdn ends with pat, this is because at a time Firebase chooses to switch to pat, I am not really sure why. Just go with the flow. You can get a similar CDN from here.

3. Get the App Key (From firebase Console)

To set up the getToken function you will need an App key this key can be found in the Firebase console.

Log in or create an account Firebase console You will need to select your Firebase app or create one. One in the page below just click on your app.

Next, you click on the setting icon and select Project Settings

Then locate the Cloud Messaging Tab

Scroll down, at the bottom you will see an option to create an app key pair. Create one and copy it(save it for later)

4. Get the Firebase config (From firebase Console)

Now we need the Firebase config file to set up the client. You can find it in the general tab in the project settings. Copy the above config and save.

Note: From Firebase v8 and later you must add all properties of the config.

5. Set up Firebase for notification

Now it is time for the part you've all been waiting for. At this point, we can use the config and app key to set up the code to initialize the app and create a Client Token.

First, create your HTML file and add whatever markup you like. Make sure that you have added the CDN script to the HTML file.

Next, create your script tag or a javascript file that can access the Firebase CDN. In that file begin by creating a variable for the stored app key and Firebase config, then initializing Firebase and Firebase Messaging

const app_key = "your app key";
const firebaseConfig = {
    apiKey: "your apiKey",
    authDomain: "your authDomain",
    projectId: "your projectId",
    storageBucket: "your storageBucket",
    messagingSenderId: "your messagingSenderId",
    appId: "your appId",
    measurementId: "your measurementId"
};


// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const m = firebase.messaging();

Now at this point, you have 3 things to do, you can do it however you like but I find it reasonable to do it this way.

Make a function that handles getting the user Token and sending it to you app server

function sendTokenToDB(done) {
    m.getToken({
        vapidKey: app_key
    }).then((currentToken) => {
        if (currentToken) {
            console.log('current token for client: ', currentToken);
            // Track the token -> client mapping, by sending to backend server
            // show on the UI that permission is secured
            // ... add you logic to send token to server
        }
    }).catch((err) => {
        console.log('An error occurred while retrieving token. ', err);
        // catch error while creating client token
    });
}

Next, I made a function that will display the notification once received. This function also registers the service worker

function onNotification(theNotification) {
    const { title, link_url, ...options } = theNotification;
    notification_options.data.link_url = link_url;

    if ('serviceWorker' in navigator) {
       // this will register the service worker or update it. More on service worker soon
        navigator.serviceWorker.register('./firebase-messaging-sw.js', { scope: './' }).then(function (registration) {
            console.log("Service Worker Registered");
            setTimeout(() => {
                // display the notificaiton
                registration.showNotification(title, { ...notification_options, ...options }).then(done => {
                    console.log("sent notificaiton to user");
                    const audio = new Audio("./util/sound/one_soft_knock.mp3"); // only works on windows chrome
                    audio.play();
                }).catch(err => {
                    console.error("Error sending notificaiton to user", err);
                });
                registration.update();
            }, 100);
        }).catch(function (err) {
            console.log("Service Worker Failed to Register", err);
        });
    }
}

Note: theNotification is an object that looks like this

           {
                title: "Message Title",
                body: "Message body",
                icon: "/img/icon.png",
                link_url: "http://localhost:5001"
            }

Note: notification_options is an object that contains showNotification options. For more on showNotification options see MDN This is what I used for mine

  const notification_options = {
        icon: "/img/icon.png",
        tag: "notification 1",
        badge: "/img/icon.png",
        image: "/img/background/sm.jpg",
        renotify: true,
        click_action: "/", // To handle notification click when notification is moved to notification tray
        data: {
            click_action: "/"
        }
    }

Ok now that we have made a way to send the notification, we need a way to receive the notification. To do this we need to set up the onMessage function so

// Handle ining messages. Called when:
// - a message is received while the app has focus
// - the user clicks on an app notification created by a service worker
m.onMessage(function (payload) {
    console.log("Received Notification:", payload);
    const theNotification = payload.data

    if (Notification.permission === "granted") onNotification(theNotification);
});

With this, we can not receive notifications from our server. Now the last thing to set up in this file is the Permission request. Before sending a notification you must ask user for permission to send them a notification. To ask your users for permission we can use the function below

function registerUserFCM() {
    if (!("Notification" in window)) {
        // Check if the browser supports notifications
    } else if (Notification.permission === "granted") {
        // Check whether notification permissions have already been granted;
        // if so, create a token for that user and send to server
        sendTokenToDB(done => {
            console.log("done", done);
            if (done) {
                onNotification({ title: "Successful", body: "Your device has been register", tag: "wele" });
            }
        });
    } else if (Notification.permission !== "denied") {
        // We need to ask the user for permission
        Notification.requestPermission().then((permission) => {
            // If the user accepts, create a token and send to server
            if (permission === "granted") {
                sendTokenToDB(done => {
                    console.log("done", done);
                    if (done) {
                        onNotification({ title: "Successful", body: "Your device has been register", tag: "wele" });
                    }
                });
            } else {
                alert("You won't be able to receive important notifications 

本文标签: