How to implement firebase notification / push notification on php, wordpress any website using javascript

Insert this code before closing body tag

<script type="module">
  // Import the functions you need from the SDKs you need
  import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js";
  import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-analytics.js";
  import { getMessaging, getToken } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-messaging.js";

  // TODO: Add SDKs for Firebase products that you want to use
  // https://firebase.google.com/docs/web/setup#available-libraries

  // Your web app's Firebase configuration
  // For Firebase JS SDK v7.20.0 and later, measurementId is optional
  const firebaseConfig = {
    apiKey: "AIzaSyBql0gSNeGoc4tS0rU__tfQ3A",
    authDomain: "aditya-bd972.firebaseapp.com",
    databaseURL: "https://aditya-bd972.firebaseio.com",
    projectId: "aditya-bd2=972",
    storageBucket: "aditya-bd972.appspot.com",
    messagingSenderId: "730776396949",
    appId: "1:730776396449:web:ff1174fa2aac6dfbdc46e0"
  };
  //Initialize Firebase
  const app = initializeApp(firebaseConfig);
  const analytics = getAnalytics(app);
  const messaging = getMessaging();

  getToken(messaging, { vapidKey: 'BM-QUwBccFqQAlfA2XuYNXVb7RttdqHwfv9e2a_XwQ0QoQ05VI25JDVkGhjh_bEJl9fONflY6tPvQ' }).then((currentToken) => {
  if (currentToken) {
    // Send the token to your server and update the UI if necessary
    // ...
    console.log(currentToken);
  } else {
    // Show permission request UI
    console.log('No registration token available. Request permission to generate one.');
    // ...
  }
}).catch((err) => {
  console.log('An error occurred while retrieving token. ', err);
  // ...
});


 // console.log(messaging);
 // console.log(app);
</script>

Create two file init.js and firebase-messaging-sw.js store it in root of website

Content for init.js

    // TODO: Replace the following with your app's Firebase project configuration
    
    const firebaseConfig = {
      apiKey: "AIzaSyBql0g4w_K19oc4tS0rU__tfQ3A",
      authDomain: "aditya-bd272.firebaseapp.com",
      databaseURL: "https://aditya-bd972.firebaseio.com",
      projectId: "aditya-bd972",
      storageBucket: "aditya-bd972.appspot.com",
      messagingSenderId: "730776396449",
      appId: "1:730776396449:web:ff1174fa2aac6dfbdc46e0"
    };
  
    //Initialize Firebase
  
    
    
  // Initialize Firebase with a "default" Firebase project
var defaultProject = firebase.initializeApp(firebaseConfig);

console.log(defaultProject.name);  // "[DEFAULT]"

Content for firebase-messaging-sw.js

// Import and configure the Firebase SDK
// These scripts are made available when the app is served or deployed on Firebase Hosting
// If you do not serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup
 importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
 importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
  importScripts('init.js');

var messaging = firebase.messaging();

/**
 * Here is is the code snippet to initialize Firebase Messaging in the Service
 * Worker when your app is not hosted on Firebase Hosting.
 // [START initialize_firebase_in_sw]
 // Give the service worker access to Firebase Messaging.
 // Note that you can only use Firebase Messaging here, other Firebase libraries
 // are not available in the service worker.
 importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
 importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
 // Initialize the Firebase app in the service worker by passing in the
 // messagingSenderId.
 firebase.initializeApp({
   'messagingSenderId': 'YOUR-SENDER-ID'
 });
 // Retrieve an instance of Firebase Messaging so that it can handle background
 // messages.
 const messaging = firebase.messaging();
 // [END initialize_firebase_in_sw]
 **/


// If you would like to customize notifications that are received in the
// background (Web app is closed or not in browser focus) then you should
// implement this optional method.
// [START background_handler]
messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  var notificationTitle = 'Background Message Title';
  var notificationOptions = {
    body: 'Background Message body.',
    icon: '/favicon.ico'
  };

  return self.registration.showNotification(notificationTitle,
    notificationOptions);
});
// [END background_handler]

Login in https://console.firebase.google.com/u/0/project and send notification from firebase panel



Leave a Reply