首页 > 解决方案 > Firebase 网络推送通知不起作用

问题描述

我已经为我的 PWA ionic 4 应用程序配置了网络推送通知。The web push notifications are working like a charm when the tab is switched ie in background or other than my app.

The issue is when the tab is active I get the push messaging inside application section of chrome inspection but there is no notification fired.

下面是代码:

app.component.ts

async ngOnInit() {
firebase.initializeApp(environment.firebase);
}

ngAfterViewInit() {
   this.platform.ready().then(async () => {
   await this.notificationsService.requestPermission();
   });
}

通知服务.ts

export class NotificationsService {
  init(): Promise<void> {
    return new Promise<void>((resolve, reject) => {
      navigator.serviceWorker.ready.then(
    registration => {
      // Don't crash an error if messaging not supported
      if (!firebase.messaging.isSupported()) {
        resolve();
        return;
      }

      const messaging = firebase.messaging();

      // Register the Service Worker
      messaging.useServiceWorker(registration);

      // Initialize your VAPI key
      messaging.usePublicVapidKey(environment.firebase.vapidKey);


      // Listen to messages when your app is in the foreground
      messaging.onMessage(payload => {
        console.log("Payload is here", payload);
      });
      // Optional and not covered in the article
      // Handle token refresh
      messaging.onTokenRefresh(() => {
        messaging
          .getToken()
          .then((refreshedToken: string) => {
            console.log(refreshedToken);
          })
          .catch(err => {
            console.error(err);
          });
      });

      resolve();
    },
    err => {
      reject(err);
    }
  );
});
}

因此,如果应用程序选项卡在 chrome 中打开,则触发通知时应该console.log在内部调用messaging.onMessage但它不会被执行。我在. _firebase-messaging-sw.js

标签: angularionic-frameworkionic4progressive-web-appsweb-notifications

解决方案


当您的应用程序在前台时,您的应用程序将不会收到messaging可观察的通知,但它会在messages可观察的情况下发出。

所以你应该像这样订阅它

firebase.messages.subscribe((message: any) => {
        if (message.notification) {
          // Show your notification from here
        }
      });

推荐阅读