angular / angularfire

Angular + Firebase = ❤️
https://firebaseopensource.com/projects/angular/angularfire2
MIT License
7.67k stars 2.19k forks source link

ServiceWorker for push notification (PWA) throws exception #3447

Closed Th-Barth closed 11 months ago

Th-Barth commented 11 months ago

Hello, I would like to get webpush notifications working in a test app (Ionic/Angular as a PWA). The documentation and videos I've watched on this so far are mostly outdated. So I am now trying to reproduce the sample provided here. However, I get an error message:

ERROR TypeError: ServiceWorker script at https://<subdomain>.web.app/firebase-messaging-sw.js for scope https://<subdomain>.web.app/__ threw an exception during script evaluation. main.e08daced9517a7b1.js:1:201234

I'll list the steps I've taken so far. Maybe someone can see immediately what is missing or why it doesn't work.

ionic start pwatest blank --type=angular
cd pwatest
ng add @angular/pwa
npm install -g firebase-tools
npm install firebase@9.23.0 @angular/fire --save

configure project in the firebase console to get firebaseConfig, so that ng add @angular/fire can fetch all the informations

ng add @angular/fire
ionic build --prod
firebase init 
   public directory: www  
   rewrite all urls to index.html: No
   File www/index.html already exists. Overwrite? No
   Firebase initialiszation complete

app.module.ts (imports added by ng add pwa/fire automatically)

    ServiceWorkerModule.register('ngsw-worker.js', {
      enabled: !isDevMode(),
      // Register the ServiceWorker as soon as the application is stable
      // or after 30 seconds (whichever comes first).
      registrationStrategy: 'registerWhenStable:30000'
    }),
    provideFirebaseApp(() => initializeApp(environment.firebase)),
    provideMessaging(() => getMessaging())],

angular.json (projects app ... assets)

  "src/manifest.webmanifest", 
  "src/firebase-messaging-sw.js"

manifest.webmanifest added line

  "gcm_sender_id": "103953800507",

firebase-messaging-sw.js from sample but changed to 9.23.0

import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.23.0/firebase-app.js';
import { getMessaging, onBackgroundMessage, isSupported } from 'https://www.gstatic.com/firebasejs/9.23.0/firebase-messaging-sw.js';

const app = initializeApp({
 projectId: '...',
    appId: '1....6',
    storageBucket: '....appspot.com',
    apiKey: 'A...s',
    authDomain: '....firebaseapp.com',
    messagingSenderId: '3.....3',
});

isSupported().then(isSupported => {
    console.log("firebase-messaging-sw: isSupported? ", isSupported);
    if (isSupported) {
        const messaging = getMessaging(app);

        onBackgroundMessage(messaging, ({ notification: { title, body, image } }) => {
            console.log("firebase-messaging-sw: Message received, title: ", title)
            self.registration.showNotification(title, { body, icon: image || '/assets/icons/icon-72x72.png' });
        });
    }
});

environment.ts/environment.prod.ts

export const environment = {
  firebase: {
    projectId: '...',
    appId: '1....6',
    storageBucket: '....appspot.com',
    apiKey: 'A...s',
    authDomain: '....firebaseapp.com',
    messagingSenderId: '3.....3',
  },
  vapidKey: 'BLabK.....qyJa3--oFs18',
  production: false/true
};

home.page.ts (from sample for testing added in home)

export class HomePage implements OnInit {
  token$: Observable<any> = EMPTY;
  message$: Observable<any> = EMPTY;
  showRequest = true;

  constructor(
    public readonly firebaseApp: FirebaseApp,
    @Optional() messaging: Messaging) {
    console.log('messaging', messaging);
    if (messaging) {
      this.token$ = from(
        navigator.serviceWorker.register('firebase-messaging-sw.js', { type: 'module', scope: '__' }).
          then(serviceWorkerRegistration =>
            getToken(messaging, { serviceWorkerRegistration, vapidKey: environment.vapidKey })
          )).pipe(
            tap(token => console.log('FCM here 1', {token})),
            share(),
          );
      this.message$ = new Observable(sub => onMessage(messaging, it => sub.next(it))).pipe(
        tap(token => console.log('FCM here 2', {token})),
      );
    }
  }

  ngOnInit(): void {
  }

  // found in https://github.com/angular/angularfire/issues/3369
  request() {
    Notification.requestPermission().then((permission) => {
      if (permission === 'granted') console.log('Permission granted');
      else if (permission === 'denied') console.log('Permission denied');
    });
  }

}

home.page.html (from sample)

<ion-content [fullscreen]="true">
  <p>Hello world!!! {{ firebaseApp.name }}</p>

  <p>
    Messaging!
    <code>{{ token$ | async | slice:0:12 }}<ng-container *ngIf="(token$ | async) !== null">&hellip;</ng-container></code>
    &nbsp;<code>{{ message$ | async | json }}</code>
    <button (click)="request()" *ngIf="showRequest">Request FCM token</button>
  </p>
</ion-content>

The output is:

Hello world!!! [DEFAULT]

Messaging!  null

Button: Request FCM token

Request Permission worked and could be granted. Does anyone perhaps have an idea why the evaluation is not working?

Additional Infos package.json

"dependencies": {
    "@angular/animations": "^16.2.10",
    "@angular/common": "^16.2.10",
    "@angular/compiler": "^16.2.10",
    "@angular/core": "^16.2.10",
    "@angular/fire": "^7.6.1",
    "@angular/forms": "^16.2.10",
    "@angular/platform-browser": "^16.2.10",
    "@angular/platform-browser-dynamic": "^16.2.10",
    "@angular/router": "^16.2.10",
    "@angular/service-worker": "^16.2.10",
    "@capacitor/app": "5.0.6",
    "@capacitor/core": "5.5.0",
    "@capacitor/haptics": "5.0.6",
    "@capacitor/keyboard": "5.0.6",
    "@capacitor/status-bar": "5.0.6",
    "@ionic/angular": "^7.5.1",
    "firebase": "^9.23.0",
    "ionicons": "^7.2.1",
    "rxjs": "~7.8.1",
    "tslib": "^2.6.2",
    "zone.js": "~0.13.3"
  },

ionic info

Ionic:

   Ionic CLI                     : 7.1.1 (C:\Users\thoma\AppData\Roaming\npm\node_modules\@ionic\cli)
   Ionic Framework               : @ionic/angular 7.5.1
   @angular-devkit/build-angular : 16.2.6
   @angular-devkit/schematics    : 16.2.6
   @angular/cli                  : 16.2.6
   @ionic/angular-toolkit        : 10.0.0

Capacitor:

   Capacitor CLI      : 5.5.0
   @capacitor/android : not installed
   @capacitor/core    : 5.5.0
   @capacitor/ios     : not installed

Utility:

   cordova-res : 0.15.4
   native-run  : 1.7.3

System:

   NodeJS : v18.17.1 (C:\Program Files\nodejs\node.exe)
   npm    : 9.6.7
   OS     : Windows 11
google-oss-bot commented 11 months ago

This issue does not seem to follow the issue template. Make sure you provide all the required information.

Th-Barth commented 11 months ago

Hello, this issue can be closed or even deleted. I had to recreate the firebase-messaging-sw.js file. Seems that the file was somehow corrupted!