I’m trying to set up Firebase Cloud Messaging but I’m having compatibility issues with Safari I don’t know if it’s due to the script or the test http-server I’m running it on.
Since @angular/fire is not yet standalone compatible I opted for direct interaction of Firebase interconnected with the pwa worker (@angular/pwa).
I created a firebase-setup.ts on which to include the dedicated code… the problem with Safari desktop (17.4.1) is that I get the notification acceptance request popup randomly… doing many page refreshes … at you want by clicking cmd+enter … absurd.
firebase-setup.ts
import { initializeApp } from 'firebase/app';
import { getMessaging, getToken } from 'firebase/messaging';
const firebaseConfig = {
...
};
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
navigator.serviceWorker
.getRegistration('./ngsw-worker.js')
.then((registration) => {
requestPermission(registration);
});
async function requestPermission(
registration: ServiceWorkerRegistration | undefined,
) {
return new Promise((resolve) => {
const timeoutId = setInterval(() => {
if (Notification.permission === 'granted') {
handleComplete(Notification.permission);
}
}, 3000);
const handleComplete = (permission: NotificationPermission) => {
clearInterval(timeoutId);
resolve(permission);
if (permission === 'granted') {
getToken(messaging, {
vapidKey: '...',
serviceWorkerRegistration: registration,
})
.then((currentToken) => {
if (currentToken) {
console.log(currentToken);
} else {
console.log(
'No registration token available. Request permission to generate one.',
);
}
})
.catch((err) => {
console.log('Error token ', err);
});
}
};
Notification.requestPermission(handleComplete)?.then?.(handleComplete);
});
}
main.ts
import '../firebase-setup'
app.component.ts
import { SwPush } from '@angular/service-worker';
export class AppComponent implements OnInit {
swPush = inject(SwPush)
ngOnInit(): void {
this.subscribePush()
}
subscribePush(): void {
this.swPush.messages.subscribe(
(res: any) => {
console.log(res, ' Message to show into notification')
}
)
}
}