Ahmad Gulzar
Ahmad Gulzar

Reputation: 142

Firebase Web JS, Receive notification in Background and then process it in your webpage

I am working on firebase cloud messaging.

Scenario: When my browser is in the background and I receive a Notification through Service Worker it is showing me the Notification in Browser Handler like this

enter image description here

Now if I click the notification or open the browser I am unable to fetch that notification details in the webpage,

WHAT I WANT

I want when the user clicks the notification or open the browser it should trigger a notification Through some library like TOASTR JS on my webpage so the user can interact with it to go to the desired notification page or anything I want to do here...

Service Worker FILE

importScripts('https://www.gstatic.com/firebasejs/7.22.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.22.0/firebase-messaging.js');

// Initialize Firebase
var firebaseConfig = {
    apiKey: "AIzaSyBvOpTvMo_vxMi1l3EEcd8UbbQPeW2Ktdg",
    authDomain: "educore-portal.firebaseapp.com",
    databaseURL: "https://educore-portal.firebaseio.com",
    projectId: "educore-portal",
    storageBucket: "educore-portal.appspot.com",
    messagingSenderId: "1038865124281",
    appId: "1:1038865124281:web:26a7ae36c7819a170f8468",
    measurementId: "G-N8PGZHM0P5"
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();


// 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
    const notificationTitle = 'Background Message Title';
    const notificationOptions = {
        body: 'Background Message body.',
        icon: '/firebase-logo.png'
    };

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

messaging.onBackgroundMessage((payload) => {
    console.log('Message received.onBackgroundMessage ', payload);
});

INIT OF FIREBASE FUNCTION

function initFirebase() {
    var firebaseConfig = {
        apiKey: "AIzaSyBvOpTvMo_vxMi1l3EEcd8UbbQPeW2Ktdg",
        authDomain: "educore-portal.firebaseapp.com",
        databaseURL: "https://educore-portal.firebaseio.com",
        projectId: "educore-portal",
        storageBucket: "educore-portal.appspot.com",
        messagingSenderId: "1038865124281",
        appId: "1:1038865124281:web:26a7ae36c7819a170f8468",
        measurementId: "G-N8PGZHM0P5"
    };
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
    const messaging = firebase.messaging();
    messaging.usePublicVapidKey("BJ3u-j-0W2m1it06nryDvW8dV9X7uzl6i9la_lyEKPLYkmZHVxqGpCwF8l-vXCHx6sAcOa3O2WGnVdAsVbA2-Rc");
    // Get Instance ID token. Initially this makes a network call, once retrieved
    // subsequent calls to getToken will return from cache.
    messaging.getToken().then((currentToken) => {
        if (currentToken) {
            console.log('currentToken', currentToken);
        } else {
            // Show permission request.
            console.log('No Instance ID token available. Request permission to generate one.');
        }
    }).catch((err) => {
        console.log('An error occurred while retrieving token. ', err);
    });


    // Handle incoming messages. Called when:
    // - a message is received while the app has focus
    // - the user clicks on an app notification created by a service worker
    //   `messaging.setBackgroundMessageHandler` handler.
    messaging.onMessage((payload) => {
        console.log('Message received. ', payload);
        toastr["info"](payload.notification.body, payload.notification.title);
        // ...
    });

}

Upvotes: 3

Views: 2675

Answers (1)

Ahmad Gulzar
Ahmad Gulzar

Reputation: 142

I tried to search for a way to trigger the notification inside my Web page while it is received when the browser is in the background. But i did not found any solution that is linked with the Firebase.

So What i think of is to use the Document visibility change Event listener

This is a basic structure of how to use it. It will be called every time the visibility state of the tab is changed. So whenever the user is coming back to my web page i am calling function to check for new messages if found then trigger other functions to show notification or refresh the chat messages etc....

Hope it will help you guys...

document.addEventListener("visibilitychange", function() {
  console.log( document.visibilityState );
  //Run code snippet and switch the tab/browser and come back again
  //hidden
  //visible
});

Upvotes: 3

Related Questions