integrate Firebase web notification in the laravel application

integrate Firebase web notification in the laravel application
integrate Firebase web notification in the laravel application

Hi guys,

Web notifications are messages sent to a visitor’s device from a website. It allows you to engage and retain website visitors. Push notification can boost app engagement by 88%, with 66% of app users on average returning to that app when push enabled.

In this article, we are using Firebase and Laravel & VueJs technology. We will consider setting up push notifications in the SPA application. We will learn step by step the integration of FCM in Laravel.

Firebase Notification integration laravel

Step 1-

We are preparing a project on the firebase console. Click here to https://console.firebase.google.com/. I am enabling google analytic for a report.
It will take less than 1 minute to create a project for you.

  • Click to Add Project
  • Add New to Web App
  • Google Anayltics Checks
  • Click to Create Project
  • Wait to complete process
  • Goto Project Setting
  • Copy the contain of rectangle
  • Create WebApp in General Tab
  • Give the Name of Project
  • Copy the code

Step 2-

Click your project and click the setting icon and click project settings. Go to the Cloud Messaging tab. Make sure that you should copy the server key and senderID.

Step 3-

Click to create the keypair button.

Step 4-

Goto General Tab, scroll down a little. We need to create a web app.

Step 5-

Enter web app name and click register.

Step 6-

I am using `<script>` tag. copy the script and paste it on your application. A user visits your application. It will see the permission box in their browser.

Step 7-

Install firebase and firebase-messaging packages on your application.

npm install --save [email protected]

npm i @firebase/messaging@^0.9.6

Step 8-

You can add the following code on the bootstrap.js file and add your firebase credential on the .env file.

import firebase from "firebase/app";
import "firebase/messaging";

var firebaseConfig = {
  apiKey: process.env.MIX_FIREBASE_API_KEY,
  authDomain: process.env.MIX_FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.MIX_FIREBASE_DATABASE_URL,
  projectId: process.env.MIX_FIREBASE_PROJECT_ID,
  storageBucket: process.env.MIX_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.MIX_FIREBASE_MESSAGING_SENDERID,
  appId: process.env.MIX_FIREBASE_APPID,
};

firebase.initializeApp(firebaseConfig);
    if ("Notification" in window) {
      const messaging = firebase.messaging();
      try {
        messaging.getToken({
          vapidKey: process.env.MIX_FIREBASE_VAPIDKEY,
        }).then((currentToken) => {
          if (currentToken) {
            sendTokenToServer(currentToken);
          } else {
            console.warn("Failed to get token.");
          }
        }).catch((err) => {
          console.log("An error occurred while retrieving token. ",err);
          this.setTokenSentToServer(false);
        });
      } catch (e) {
        console.log(e);
      }
      messaging.onMessage((payload) => {
        payload = JSON.parse(payload.data.data);
        console.log("Message received. firebase.js ", payload);
        new Notification(payload.title, {
              body: payload.message,
              icon: payload.image
            });
      });
    }

Step 9-

You get the token from the firebase console and store it in your database. When the admin completes the process, the user will get notified. Now, you need to register with the JavaScript worker. The user will get a notification in the background and display them. You need to create a firebase-messaging-sw.js file in the public directory and add the below code.


importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js');
try 
{
    firebase.initializeApp({
        apiKey:MIX_FIREBASE_API_KEY,
        authDomain: MIX_FIREBASE_AUTH_DOMAIN,
        databaseURL: MIX_FIREBASE_DATABASE_URL,
        projectId: MIX_FIREBASE_PROJECT_ID,
        storageBucket: MIX_FIREBASE_STORAGE_BUCKET,
        messagingSenderId: MIX_FIREBASE_MESSAGING_SENDERID,
        appId: MIX_FIREBASE_APPID,
    });
    var messaging = firebase.messaging();
    self.addEventListener("notificationclick", function (event) {
        const target = event.notification.data.click_action || "/";
        event.notification.close();
        // This looks to see if the current is already open and focuses if it is event.waitUntil(
        clients.matchAll({
            type: "window",
            includeUncontrolled: true,
        }).then(function (clientList) {
        // clientList always is empty?!
        for (var i = 0; i < clientList.length; i++) {
            var client = clientList[i];
                if (client.url === target && "focus" in client) {
                return client.focus();
                }
            }
            return clients.openWindow(target);
        })

        messaging.onBackgroundMessage((payload) => {
            console.log("[firebase-messaging-sw.js] Received background message ",payload );
            // Customize notification here
            const notificationTitle = payload.notification.title;
            const notificationOptions = {
                body: payload.notification.message,
                icon: payload.notification.image
            };
            self.registration.showNotification(
                notificationTitle,
                notificationOptions
            );
        });
    });
} catch(e) {
    console.log(e)
}

Step 10-

You can register as a service worker to your application in your main view. Add the below code in the view file.

<script>
            if ('serviceWorker' in navigator) {
                navigator.serviceWorker.register('../firebase-messaging-sw.js')
                .then(function(registration) {
                    console.log('Registration successful, scope is:', registration.scope);
                }).catch(function(err) {
                    console.log('Service worker registration failed, error:', err);
                });
            }
        </script>

We successfully integrate Firebase web notification in the laravel application. Now you can enjoy the firebase web notification on your application.

Thank you for reading this article. Please share this article with your friend circle. That’s it for the day. Stay Connected!
Cheers

Name
Email
The form has been submitted successfully!
There has been some error while submitting the form. Please verify all form fields again.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top