Notifications in service workers inside Chrome extension

270 views
Skip to first unread message

Joshua Weaver

unread,
Jun 25, 2019, 6:28:25 PM6/25/19
to Chromium Extensions
So I have a Chrome extension that is using firebase for messaging and its behaving differently than I would expect. 

Here's what I'm doing:
  1. I register a service worker for messages sent while app is in the background, and I have onMessage handlers for foreground messages.  
  2. I setup the listener for receiving messages in the service worker and in the background.js file. 
  3. When I hit the correct HTTP call to fire off a firebase push notification, the service worker method setBackgroundMessageHandler() gets called correctly as I can see when I'm debugging.
    However, the notification is never shown! Note: the payload does NOT have a "notifications" key in it.
SERVICE WORKER CODE - firebase-sw.js
import firebase from './firebase';
import 'firebase/messaging';

const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler( ( payload ) => {
   
console.log( '[firebase-sw.js] Received background message ', payload );
   
// Customize notification here
    let notificationTitle = 'Background Message Title';
   
let notificationOptions = {
       
body: 'Background Message body.',
   
};

   
// THIS CODE NEXT LINE DOESN'T HAVE ANY EFFECT!
   
return self.registration.showNotification( notificationTitle, notificationOptions );
} );
^ (code is almost directly pulled from https://firebase.google.com/docs/cloud-messaging/js/receive)


BACKGROUND.js
import firebase from './firebase';
import 'firebase/messaging';
const messaging = firebase.messaging();
messaging.usePublicVapidKey( 'BByfoHTu_xmuusRLf12mqTfdcqd33nLOl9KEP75p-vw42KmKQMkaJ6r11QRTS77eF0je8lKEbTw4Y0ZXFISeUB8' );

// FOREGROUND listener
messaging.onMessage( ( message ) => {
   
console.log( message );
   
debugger;
} );

// REGISTER SERVICE WORKER
navigator.serviceWorker.register( chrome.extension.getURL( '/firebase-sw.js' ) )
   
.then( ( registration ) => {
       
messaging.useServiceWorker( registration );
       
messaging.getToken().then( ( token ) => {
           
console.log( token );
       
} );
   
} )
   
.catch( ( error ) => console.log( 'error registering service worker: ', error ) );




I have 2 questions:

  1. Why doesn't a notification fire when the payload comes in? (see setBackgroundMessageHandler() method where I call 
    self.registration.showNotification( notificationTitle, notificationOptions );

  2. If I'm listening in a background script for the onMessage event, that is pointless since the background page is ALWAYS in the background, so the service worker will always handle the incoming message right? Can I listen for firebase.messaging().onMessage() in a context script?
Reply all
Reply to author
Forward
0 new messages