1

I'm currently developing a google chrome extension where I need to receive push notifications. For that, I use Firebase Cloud messaging.

The token is correctly send and I can send a notification with postman which i receive on my google chrome.

However, onMessage and setBackgroundMessageHandler are never trigger, it's like the notification is totally independent.

Here is my code :

background.js

chrome.runtime.onInstalled.addListener(function() {

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('../firebase-messaging-sw.js');
} else {
    console.warn('Service workers aren\'t supported in this browser.');
}

firebase.initializeApp({
    apiKey: "xx",
    authDomain: "xx",
    databaseURL: "xx",
    projectId: "xx",
    storageBucket: "xx",
    messagingSenderId: "xx",
    appId: "xx"
});

const messaging = firebase.messaging();
messaging.usePublicVapidKey("xx");

// WORK WELL
messaging.requestPermission()
.then(function() {
    console.log("=== have permission ===");
    return messaging.getToken();
})
.then(function(currentToken) {
    console.log("Set token : ", currentToken);
    chrome.storage.sync.set({fcmToken: currentToken}, function() {});
})
.catch(function(err) {
    console.log("==== error ====", err);
});

messaging.onTokenRefresh(() => {
    messaging.getToken().then((refreshedToken) => {
        console.log("Refresh token : ", refreshedToken);
        chrome.storage.sync.set({fcmToken: refreshedToken}, function() {});
    }).catch((err) => {
        console.log('Unable to retrieve refreshed token ', err);
    });
});

//Never trigger 
messaging.onMessage((payload) => {
    chrome.browserAction.setBadgeText({text: "1"});
    console.log('Message received. ', payload);
});

firebase-messaging-sw.js

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

firebase.initializeApp({
    apiKey: "xx",
    authDomain: "xx",
    databaseURL: "xx",
    projectId: "xx",
    storageBucket: "xx",
    messagingSenderId: "xx",
    appId: "xx"
});

const messaging = firebase.messaging();

// NEVER TRIGGER
messaging.setBackgroundMessageHandler(function(payload) {
    console.log('[firebase-messaging-sw.js] Received background message ', payload);
    const notificationTitle = 'Background Message Title';
    const notificationOptions = {
      body: 'Background Message body.',
      icon: '/firebase-logo.png'
    };

    return self.registration.showNotification(notificationTitle,
      notificationOptions);
});

manifest.json

{
"manifest_version": 2,
"name": "app",
"description": "app",
"version": "0.0.3",
"permissions": [
    "http://*/*",
    "https://*/*",
    "storage",
    "notifications"
],
"web_accessible_resources": [
    "js/popup.js",
    "css/popup.css",
    "html/popup.html",
    "html/background.html",
    "js/background.js"
],
"background": {
    "page": "html/background.html",
    "persistent": false
},
"options_page": "html/options.html",
"browser_action": {
    "default_title": "Notification",
    "default_popup": "html/popup.html",
    "default_icon": {
      "128": "img/get_started128.png"
    }
},
"content_security_policy": "script-src 'self' https://www.gstatic.com/ https://*.firebaseio.com https://www.googleapis.com; object-src 'self'",
"icons": {
  "128": "img/get_started128.png"
}

}

Thanks a lot if you have the answer !

Have a good day, Gabin

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Gabin
  • 11
  • 2
  • Remove `web_accessible_resources`, you should never expose internal extension pages as they can't be used outside of extension environment anyway. Are you opening background.html in a tab? It won't work. The background page is a special hidden page (see [Where to read console messages from background.js in a Chrome extension?](https://stackoverflow.com/a/10258029)). – wOxxOm Apr 23 '20 at 04:00
  • Ok thanks for web_accessiblhtml. I don't look in a tab I look in the console message like in your link. – Gabin Apr 23 '20 at 17:15
  • @Gabin I am able to receive the notification in the setBackgroundMessageHandler (service worker) but not in onMessage(background.js). Were you able to solve this issue? In my case, I want to have my own notification UI instead of the default notifications from chrome. – Asha Joshi Sep 06 '20 at 01:45

1 Answers1

0

onMessage and setBackgroundMessageHandler are only triggered when you receive the message from the background and not in the foreground.

In the docs, it mentioned you can receive msg on two: foreground, background.

If you want to log/see push messages from service worker you can use:

    this.push(event)=>{
          console.log(event.data)
    }
Harsh Goel
  • 166
  • 1
  • 7