【问题标题】:Firebase web push notification not working messaging.onMessageFirebase 网络推送通知不起作用
【发布时间】:2020-06-11 18:54:46
【问题描述】:

我已将网络推送通知配置到我的 PWA ionic 4 应用程序。当标签页切换时,即在后台或我的应用程序之外,网络推送通知就像一个魅力。

问题是当标签处于活动状态时,我在 chrome 检查的应用程序部分收到推送消息,但没有触发任何通知。

下面是代码:

app.component.ts

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

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

notifications.service.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 中打开,则触发通知时应该在 messaging.onMessage 内调用 console.log,但它不会被执行。 我在 firebase-messaging-sw.js 中使用 firebase 版本的 7.8.0

【问题讨论】:

标签: angular ionic-framework ionic4 progressive-web-apps web-notifications


【解决方案1】:

我遇到了完全相同的问题,实际上我在post 中找到了答案。在推送通知方面,PWA 仍然存在一些限制。

【讨论】:

    【解决方案2】:

    当您的应用程序在前台时,您的应用程序将不会收到messaging observable 的通知,但它会在messages observable 上发出。

    所以你应该像这样订阅它

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

    【讨论】:

      猜你喜欢
      • 2020-10-15
      • 1970-01-01
      • 1970-01-01
      • 2017-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多