skip to Main Content

I am having big problems, i am currently developing an App where i need to send Push Notifications to my Web App(User has to install the PWA on their mobile device). We had a lot of problems adding the App to the AppStore(iOS) so we decided to switch to full web flutter development, because restarting the project would not be feasible, since it is a huge project already.
The problem now is, that I have added FCM to the App and receiving the Notifications is very problematic on different devices. I have added the firebase-messaging-sw.js file with the firebaseConfig.
The problem is that i constantly receive 2 notifications when sending them(same happens on mobile devices, edge here is just used for testing purposes on my pc)

here

My index.html file contains this script

<script>
   if ('serviceWorker' in navigator) {
      window.addEventListener('load', function () {
        navigator.serviceWorker.register('/firebase-messaging-sw.js');
      });
  }
</script>

And in the firebase-messaging-sw.js file i have these functions to receive the backgroundmessage and i added a Notificationclick event like this, because it is very important for the app to work properly to be forwarded to the source=notification window

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

const firebaseConfig = {
  apiKey: "xxxx",
  authDomain: "xxxxx",
  databaseURL: "xxxx",
  projectId: "xxxxx",
  storageBucket: "xxxx",
  messagingSenderId: "xxxxx",
  appId: "xxxxxx"
};

firebase.initializeApp(firebaseConfig);

const messaging = firebase.messaging();

let darkPatternsValue = 0;

self.addEventListener('message', function(event){
  if (event.data && event.data.type === 'SET_DARK_PATTERNS_VALUE') {
    darkPatternsValue = event.data.value;
  }
});

messaging.onBackgroundMessage(function(payload) {
    console.log('Received background message ', payload);
    if(darkPatternsValue != 1){
      return;
    }
    lastNotificationId = currentNotificationId;

    const notificationTitle = payload.notification.title;
    const notificationOptions = {
        body: payload.notification.body,
      };

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

self.addEventListener('notificationclick', function(event) {
    console.log('Notification clicked ', event);
    event.notification.close();
    event.waitUntil(
        clients.openWindow('/?source=notification')
    );
 });

This is the value i send to the service worker, to turn off notifications for darkpatterns

void sendDarkPatternsValue() async {
    html.window.navigator.serviceWorker?.getRegistrations().then((registrations) {
      for (final registration in registrations) {
        registration.active?.postMessage({'type': 'SET_DARK_PATTERNS_VALUE', 'value': 1});
      }
    });
  }

Why are there constantly 2 service workers running when i clearly only add 1?

The normal one, which is called http://localhost:xxxxxx/ and a 2nd one which is called http://localhost:xxxxxx/firebase-cloud-messaging-push-scope. How can i remove the firebase-cloud-messaging-push-scope, because even though i have the darkPatternsValue set to 0, there is still 1 notification received which does not trigger the ‘notificationclick’ event and when it is set to 1, i receive 2 notifications. But only the 2nd one triggers the ‘notificationclick’ event
Here you can see that there are 2 service workers, which should not be the case. I do not know where the top one comes from:
enter image description here

Here you can see the Receiption of the Notification in the Background services Tab enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    I found the problem, it is in the

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

    There it says

    return self.registration.showNotification(null !== (n = e.title) && void 0 !== n ? n : "", e)
    

    i copy and pasted the firebase-messaging-compact.js and imported the script via:

    importScripts('/firebase-messaging-custom.js');
    

    and replaced the line with return null. Now the notification is not shown anymore and i can use my own implementation, which has a notificationClick function. Which is stupid that i have to do it like that, but now it seems to work.


  2. You can unregistering any previous service workers before registering a new one. This can be done by calling navigator.serviceWorker.getRegistrations() and then using registration.unregister() for each registration.

    if ('serviceWorker' in navigator) {
      window.addEventListener('load', async function () {
        const registrations = await navigator.serviceWorker.getRegistrations();
    
        for (const registration of registrations) {
          await registration.unregister();
        }
    
        await navigator.serviceWorker.register('/firebase-messaging-sw.js');
      });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search