首页 > 解决方案 > 当应用程序在后台时,如何让服务人员处理推送?

问题描述

我正在使用 firebaseGuzzleHTTP从我的laravel应用程序中向我的网站用户发送消息。据我了解,有两种处理推送的方法,一种是使用消息,另一种是将对象notification包装在. 使用 FirebaseAPI,但这似乎并没有在后台运行。它仅在用户在最后几分钟内打开 PWA 时才有效。无论用户上次打开浏览器是什么时候,我都想向他们发送通知。我知道我应该为此使用 eventListener 并且我确实为它放置了代码,但我似乎总是收到 firebase API 通知(当网站最近打开时)或根本没有通知。notificationdatanotificationpush

这是我的 Firebase 消息处理程序

messaging.setBackgroundMessageHandler(function(payload) {
  // Customize notification here
  var recep = JSON.stringify(payload);
  recep = JSON.parse(recep);
  var notification = recep.notification;
  //notification = JSON.stringify(notification);
  message = JSON.parse(notification);
  const notificationTitle = message.title;
  const notificationOptions = {
    body: message.body,
    icon: message.icon,
    badge: '/img/favicon.png',
    click_action: messaging.click_action
  };

  return self.registration.showNotification(notificationTitle,
      notificationOptions);
});

这是我的服务人员消息或push处理程序:

self.addEventListener('push', function(e) {
  var body;

  if (e.data) {
    body = e.data.json().notification.body;
  } else {
    body = 'Alert from AppMate.Open the app to view details!';
  }

  var options = {
    body: body,
    icon: 'img/favicon.png',
    badge: 'img/favicon.png',
    vibrate: [100, 50, 100],
    data: {
      dateOfArrival: Date.now(),
      primaryKey: 1
    },
    actions: [
      {action: 'ap-mate', title: 'Visit AppMate!'}
    ]
  };
  e.waitUntil(
    self.registration.showNotification('Appmate Notification', options)
  );
});

这是通过以下方式发送到端点的请求GuzzleHTTP

        $message = [
            'data' => [
               'notification' => [
                 'title' => $title,
                 'body' => $body,
                 'icon' => 'img/favicon.png',
                 'badge' => 'img/favicon.png'
             ],
            ],
            'notification' => [
                'title' => $title,
                'body' => $body,
                'icon' => 'img/favicon.png',
                'badge' => 'img/favicon.png',
                'click_action' => $action
            ],
            'to' => $reg_id
        ];
        $client = new Client([
            'headers' => [
                'Content-Type' => 'application/json',
                'Authorization' => 'key='.$access_token,
            ]
        ]);
        $response = $client->post('https://fcm.googleapis.com/fcm/send',
            ['body' => json_encode($message)]
        );
        return $response->getBody();

标签: javascriptfirebasefirebase-cloud-messagingservice-workerweb-push

解决方案


推荐阅读