简体   繁体   中英

Firebase Cloud Messaging in a google chrome extension

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

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)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM