For Firebase 9.5.0 push notifications, we have a service worker that receives firebase push, the service workers all work fine.
However, we're migrating from an old service worker registration (from a 3rd party) to our own, brand new users all work fine registering and getting a token, but we get an error when we want to use a new service worker for an existing registered user (with an old service-worker from a 3rd party).
The error happens on getToken which causes the error
FirebaseError: Messaging: A problem occurred while subscribing the user to FCM:
Request is missing required authentication credential.
Expected OAuth 2 access token, login cookie or other valid authentication credential.
I'm hoping we can add some code in the catch to do something like reregister the user or something, but looking through the firebase docs, I can't find anything how we would register the user with ourselves without an error ?
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.5.0/firebase-app.js";
import { deleteToken, getMessaging, getToken, isSupported, onMessage } from "https://www.gstatic.com/firebasejs/9.5.0/firebase-messaging.js";
const firebaseConfig = {
apiKey: ...
authDomain: ...
projectId: ...
storageBucket: ...
messageSenderId: ...
appId: ...
measurementId: ...
};
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
const registerServiceWorker = () => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('serviceworkerfilename.js')
.then( function( registration) {
console.log('reg successful', registration); // gets here ok
getToken( messaging, { serviceWorkerRegistration: registration } )
.then(function(currentToken) {
// do stuff, this normally works for a new user, but not on old service worker
})
.catch( function(err) {
// always gets here for old user from old service worker
Notification.requestPermission().then(function(permission) {
console.log(permission); // gets here, and shows 'granted', but stuck from here what we can do to reset the user
});
});
})
}
}
So I got around this firstly with a check to check with filename the serviceworker had
navigator.serviceWorker.controller.scriptURL.match(<someregex>)
And then if wanted, unregister the existing service worker...
navigator.serviceWorker.getRegistrations()
.then( function(registrations) {
for(let registration of registrations) {
registration.unregister();
}
});
And then if necessary, call a function to register again.