Angular 7 PWA配置推送通知

Chr*_*ris 5 push-notification service-worker web-push progressive-web-apps angular

我正在使用角度7创建一个PWA,但我正在努力推送通知.

我下面的教程为这个这个使用SWPush,索然无味密钥对.我可以订阅和退订和我的服务器部分工作为好,但不幸的是教程不包括显示应用程序的实际通知.

据我所知,通知会自动弹出而不在代码中调用它,对吧?你只需订阅,其余的就是ngsw.不幸的是,他们并没有出现在我的案例中.我只能通过在代码中手动调用它们来显示它们,如下所示:

 this.swPush.messages.subscribe(
  (notification: any) => {
    console.log("received push message", notification);

    let options = {
      body: notification.body,
      icon: "assets/icon/favicon.png",
      actions: <any>notification.actions,
      data: notification.data,
      vibrate: [100, 50, 10, 20, 20]
    };
    this.showNotification(notification.title, options)
  },

  err => {
    console.error(err);
  }
);

[...]

showNotification(title: string, options: NotificationOptions) {
    navigator.serviceWorker.getRegistration().then(reg => {
      reg.showNotification(title, options).then(res => {
        console.log("showed notification", res)
      }, err => {
        console.error(err)
      });
   });
}
Run Code Online (Sandbox Code Playgroud)

但这似乎仅在app/page处于前台时才有效.否则,我会收到"网站已在后台更新"的通知.显然我在这里做错了什么.但是什么?

  1. 当应用程序在后台时,我该怎么做才能显示通知?

  2. 有没有办法处理通知上的点击事件?

ng文档在这里非常稀疏.

Chr*_*ris 5

经过大量的努力,我发现了一些东西并将其分享给他人:

深入研究通过运行build --prod创建的ngsw-worker.js,可以使用以下功能:

onPush(msg) {
    // Push notifications without data have no effect.
    if (!msg.data) {
        return;
    }
    // Handle the push and keep the SW alive until it's handled.
    msg.waitUntil(this.handlePush(msg.data.json()));
}
...
handlePush(data) {
    return __awaiter$5(this, void 0, void 0, function* () {
            yield this.broadcast({
                type: 'PUSH',
                data,
            });

            if (!data.notification || !data.notification.title) {
                return;
            }

            const desc = data.notification;

            let options = {};
            NOTIFICATION_OPTION_NAMES.filter(name => desc.hasOwnProperty(name))
                .forEach(name => options[name] = desc[name]);
            yield this.scope.registration.showNotification(desc['title'], options);
    });
}
Run Code Online (Sandbox Code Playgroud)

由于它看起来像angular订阅并为您显示通知,因此无需订阅并以您自己的代码显示。我的发送库(https://github.com/laravel-notification-channels/webpush)遇到了问题,该问题正在发送有效载荷,如下所示:

payload = {"title":"test","actions":[{"title":"View App","action":"view_app"}],"body":"test","icon":"\/icon.png","data":{"id":"21a3804e-6d71-4a56-b513-535709c37c0f"}}
Run Code Online (Sandbox Code Playgroud)

但是angular显然希望这样:

payload = {
    "notification":{"title":"test","actions":[{"title":"View App","action":"view_app"}],"body":"test","icon":"\/icon.png","data":{"id":"21a3804e-6d71-4a56-b513-535709c37c0f"}}
}
Run Code Online (Sandbox Code Playgroud)

这导致ngsw-worker.js中的这一行失败:

if (!data.notification || !data.notification.title) {
    return;
}
Run Code Online (Sandbox Code Playgroud)

因此,没有显示通知,但是浏览器在后台报告了更新。希望这对某人有帮助。