Search code examples
javascriptfirebase-cloud-messaging

Error Firebase Cloud Message in obtaining a token when clearing storage(clear-site-data)


I'm working with firebase and vue 3. I'm trying to implement notifications, everything works, but as soon as I clear storage(clear site data), I can't get a token for notifications, reloading the page helps solve this problem. Why is there no token receipt when clearing storage and then launching the application?

  1. The first launch of the application(work)
  2. Open the console, go tothe application
  3. Click Storage After that, click Clean Site Data
  4. Reloading the page We get an error(error below)
  5. Rebooting again solves this problem.

Error message: An error occurred while retrieving token. DOMException: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker

firebase-messaging-sw.js

importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js')
firebase.initializeApp({...})

const messaging = firebase.messaging();

messaging.onBackgroundMessage((payload) => {
  console.log(
    '[firebase-messaging-sw.js] Received background message ',
    payload
  );
  // Customize notification here
  const notificationTitle = payload.notification.title;
  const notificationOptions = {
    body: payload.notification.body,
    icon: payload.notification.image
  };

  self.registration.showNotification(notificationTitle, notificationOptions);
});
const approvedNotification = async () => {
  let permission = await Notification.requestPermission();
  if (permission === "granted") {
    getToken(messaging, { vapidKey: '...' }).then((currentToken) => {
      if (currentToken) {
        token.value = currentToken
        console.log('token:', currentToken)
        // Send the token to your server and update the UI if necessary
        // ...
      } else {
        // Show permission request UI
        console.log('No registration token available. Request permission to generate one.');
        // ...
      }
    }).catch((err) => {
      console.log('An error occurred while retrieving token. ', err);
      // ...
    });
  } else {
    // Handle denied permission
  }
}

onMounted(() => {
  approvedNotification()
})

`

I tried to change the version from 8.10 to a more recent one, but there was an error getting the token, maybe it should be rewritten firebase-messaging-sw.js


Solution

  • I fixed the error, I had to register service worker firebase-messaging-sw.js scope '/firebase-cloud-messaging-push-scope' . If you do not do this, then the first one is registered sw.js scope '/' and only after that comes the scope I need. The order in which scope registration takes place was important, keep this in mind. Be sure to specify the scope and follow the order. Here is the code that solves my problem:

    onMounted(async () => {
      onMessage(messaging, (payload) => {
      alert(payload.messageId)
      });
      // Registering Service Worker
      const serviceWorkerRegistration: any = await navigator.serviceWorker.register("/firebase-messaging-sw.js", {scope: "/firebase-cloud-messaging-push-scope"})
        .catch((err) => { return console.log('[Service Worker] Registration Error:', err) })
      if ('scope' in serviceWorkerRegistration) {
        console.log('[Service Worker] Registered. Scope:', serviceWorkerRegistration.scope)
      }
    
      await navigator.serviceWorker.ready; // Here's the waiting
    
    
      await  approvedNotification()
    })