firebase / firebase-js-sdk

Firebase Javascript SDK
https://firebase.google.com/docs/web/setup
Other
4.86k stars 895 forks source link

deleteToken does not support `serviceWorkerRegistration` option like getToken #8621

Open minht11 opened 1 month ago

minht11 commented 1 month ago

Operating System

all

Environment (if applicable)

all

Firebase SDK Version

10.14.1

Firebase SDK Product(s)

Messaging

Project Tooling

n/a

Detailed Problem Description

When using getToken your function you can provide your own service worker registration file, not needing it to be name firebase-messaging-sw.js it all works fine with getToken, but if you use deleteToken firebase throw an error:

Failed to delete Firebase token FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for

with no way to pass the same options.

Steps and code to reproduce issue

Same as description

google-oss-bot commented 1 month ago

I couldn't figure out how to label this issue, so I've labeled it for a human to triage. Hang tight.

hsubox76 commented 1 month ago

I glanced through the code briefly and it looks like the way it's supposed to go is:

  1. When getToken() is called with a custom service worker registration, it adds that registration to the MessagingService instance as messaging.swRegistration.
  2. When deleteToken() is called, it checks to see if messaging.swRegistration is populated, and if not, it tries to register the default service worker. https://github.com/firebase/firebase-js-sdk/blob/caf30900795c577be7f8db3c7437ee3f3992aee6/packages/messaging/src/api/deleteToken.ts#L31

It seems like if getToken() is called before deleteToken(), then messaging.swRegistration should exist, and it should skip this conditional.

Is deleteToken() being called in your code without having called getToken() first? Is there a use case for that?

minht11 commented 1 month ago

Is deleteToken() being called in your code without having called getToken() first? Is there a use case for that?

Likely. I am calling getToken when initially asking for notifications and when user logins and deleteToken when logouting. Should that be done on each page load instead?

hsubox76 commented 1 month ago

Yes, I think that you probably should call getToken() every time your web app is loaded, otherwise you instantiate a messaging instance with no awareness of the registration. It shouldn't make an additional network call if it still has a valid token, if you're worried about that - it should be able to retrieve the token locally from indexedDB.

I think this should fix your problem for now, I'll leave it up to the FCM team if they think a serviceWorkerRegistration option on deleteToken is a feature they think should be added.