单击@ angular/service-worker推送通知的操作部分

Bol*_*ipo 5 angular5

我一直在尝试将用户重定向到来自后端(PHP)的Webpush的"动作"部分.

    return (new WebPushMessage)
        ->title('Title')
        ->icon('icon.png')
        ->body('Body Msg')
        ->action('Open Notification', 'open_notification')
        ->data(['id' => $notification->id,'url'=>'http://somewhere']);
Run Code Online (Sandbox Code Playgroud)

默认服务工作者使用:

self.addEventListener('notificationclick', function(event) {
    console.log('On notification click: ', event.notification.tag);
    event.notification.close();

    // This looks to see if the current is already open and
    // focuses if it is
    event.waitUntil(clients.matchAll({
       type: "window"
    }).then(function(clientList) {
       for (var i = 0; i < clientList.length; i++) {
          var client = clientList[i];
              if (client.url == '/' && 'focus' in client)
                 return client.focus();
       }
       if (clients.openWindow)
          return clients.openWindow('/');
    }));
});
Run Code Online (Sandbox Code Playgroud)

来自https://developer.mozilla.org/en-US/docs/Web/Events/notificationclick

Angular 5使用

import {SwPush, SwUpdate} from '@angular/service-worker'; 
Run Code Online (Sandbox Code Playgroud)

那么我的问题是如何使用@ angular/service-worker在前端(Angular 5)中解释这一点

Bol*_*ipo 6

得到了回复u-ryo在Github上的回复

有一个解决方法.将下面的代码添加到围绕this.scope.addEventListener('push',(event)=> this.onPush(event))行的ngsw-worker.js;(第1775行).

  this.scope.addEventListener('notificationclick', (event) => {
    console.log('[Service Worker] Notification click Received. event', event);
    event.notification.close();
    if (clients.openWindow && event.notification.data.url) {
      event.waitUntil(clients.openWindow(event.notification.data.url));
    }
  });
Run Code Online (Sandbox Code Playgroud)

然后,您可以在"notification.data.url"中指定URL.

https://github.com/angular/angular/issues/20956#issuecomment-374133852

  • @BolajiPemipo我使用角度7.我发现这个很好的教程:http://jakubcodes.pl/2018/06/13/enhancing-angular-ngsw/并为点击部分注册了第二个自定义sw - 它工作得很好至今.不管怎么说,多谢拉 (4认同)