webpush.sendNotification - NotificationEvent.notification.data null - PullRequest
0 голосов

Настройка

Операционная система : Linux Версия узла : 10.15.3 Версия web-push : 3.3.4

  • [X] Хром
  • [] Firefox
  • [] Opera для Android
  • [] Интернет-браузер Samsung
  • [] Другое

Chrome: версия 74.0.3729.131 (официальная сборка) (64-разрядная версия)

Проблема

Я пытаюсь реализовать пример шага 5.2 из google pwa lab

Если я отправляю уведомление из моего скрипта node / main.js, я получаю визуальное уведомление на моем экране. Если я нажимаю на уведомление, я вижу в консоли следующее сообщение:

Uncaught TypeError: Cannot read property 'primaryKey' of null
    at sw.js:30

Если я проверяю содержимое объекта NotificationEvent.notification.data, это null .

Ожидаемое

Если я нажму на уведомление, отправленное с моего сервера узлов, я смогу увидеть данные из объекта NotificationEvent.notification.

Используемые функции

  • [x] VAPID Поддержка
  • [] Ключ API GCM
  • [x] Отправка с полезной нагрузкой

Пример / Воспроизвести дело

Это мой узел / main.js, отвечающий за веб-push-уведомления.

const webPush = require('web-push');

const pushSubscription = {
    endpoint: 'https://fcm.googleapis.com/fcm/send/flcWNQgYeVw:APA91bHgAC5M-WeyN5RNdSprIDUalAxSMznny3-QwPf2T8whtWwmtZ6Q546Pry-JCZqjSh9bbEIS778lJD7Hq-t4KLS35X6-T7dJGCnc_ECzKvsdOAQ50wlzQ5Tcm1WNvgOOwXV',
    expirationTime: null,
    keys: {
        p256dh: 'BL-Rz9Nejsd7ipsYQsQ9YB6tUc-qldkBg28y7G9LBFGdKe52sSeF0FStiKmdBp5BRFf3HazlOICBAVnY',
        auth: 'hOPxUEqXsdfFjB-MmFxaTw'
    }
};

// TODO 4.3a - include VAPID keys
const vapidPublicKey = 'MY VAPID PUBLIC KEY';
const vapidPrivateKey = 'MY VAPID PRIVATE KEY';

const payload = 'Here is a payload!';

const options = {
  //gcmAPIKey: 'NOT IN USE',
  TTL: 60,
  vapidDetails: {
      subject: 'mailto: myemail@gmail.com',
      publicKey: vapidPublicKey,
      privateKey: vapidPrivateKey
    },
    contentEncoding: 'aes128gcm'
};

webPush.sendNotification(
  pushSubscription,
  payload,
  options
).catch( error => {
    console.log(error);
}) ;

Это код моего сервисного работника, который обрабатывает уведомления:

self.addEventListener('notificationclose', event => {
  console.log(event);

  const notification = event.notification;

  const primaryKey = notification.data.primaryKey;

  console.log('Closed notification: ' + primaryKey);
});

self.addEventListener('notificationclick', event => {
  const notification = event.notification;
  console.log(notification.data);

  const primaryKey = notification.data.primaryKey;
  const action = event.action;

  if (action === 'close') {
    notification.close();
  } else {
    event.waitUntil(
      clients.matchAll().then(clis => {
        const client = clis.find(c => {
          return c.visibilityState === 'visible';
        });
        if (client !== undefined) {
          client.navigate('samples/page' + primaryKey + '.html');
          client.focus();
        } else {
          // there are no visible windows. Open one.
          clients.openWindow('samples/page' + primaryKey + '.html');
          notification.close();
        }
      })
    );
  }

  self.registration.getNotifications().then(notifications => {
    notifications.forEach(notification => {
      notification.close();
    });
  });
});

self.addEventListener('push', event => {
  let body;

  if (event.data) {
    body = event.data.text();
  } else {
    body = 'Default body';
  }

  const options = {
    body: body,
    icon: 'images/notification-flat.png',
    vibrate: [100, 50, 100],
    data: {
      dateOfArrival: Date.now(),
      primaryKey: 1
    },
    actions: [
      {action: 'explore', title: 'Go to the site',
        icon: 'images/checkmark.png'},
      {action: 'close', title: 'Close the notification',
        icon: 'images/xmark.png'},
    ]
  };
  event.waitUntil(
    clients.matchAll().then(c => {
      console.log(c);
      if (c.length === 0) {
        // Show notification
        self.registration.showNotification('Push Notification', options);
      } else {
        // Send a message to the page to update the UI
        console.log('Application is already open!');
      }
    })
  );
});

Другое

Я пытался изменить contentEncoding с aesgmc на aes128gcm, но я все еще получаю ту же ошибку.

Если я запускаю команду web-push, я вижу ту же ошибку

...