【问题标题】:How to export data received by event in service worker to vue components?如何将服务工作者中的事件接收到的数据导出到vue组件?
【发布时间】:2021-04-07 03:22:37
【问题描述】:

我正在使用 Pusher 构建通知系统。目前我有一个在 Pusher 注册的服务人员,我可以接收从我的后端发送的“通知”,但我只能在控制台中显示它们:

importScripts("https://js.pusher.com/beams/service-worker.js");

PusherPushNotifications.onNotificationReceived = ({ pushEvent, payload }) => {
  pushEvent.waitUntil(
    self.registration.showNotification(payload.notification.title, {
      body: payload.notification.body,
      icon: payload.notification.icon,
      data: payload.data
    })
  );
  let notification = `Data recieved from notification ${payload.data.message}`;
  console.log(notification);
};

我想将变量“notifications”导出到我的 vue 组件中,以操纵来自后端的信息。

我已尝试导出,但没有成功。

Service Worker 被放置在“public”文件夹中。

我该怎么做?

【问题讨论】:

    标签: vue.js service-worker pusher


    【解决方案1】:

    Service Worker 仅通过消息与页面通信。

    function postMsg(message) {
      return self.clients.matchAll().then(function(clients) {
        clients.forEach(function(client) {
          client.postMessage(message)
        });
      });
    }
    

    然后你就可以收听页面内的消息了:

    navigator.serviceWorker.onmessage = function (evt) {
      const message = evt.data
    
      if (message.type === 'notification') {
        doSomething(message)
      }
    }
    

    【讨论】:

      【解决方案2】:

      我使用广播频道能够将通知发送到我的 vue 组件。

      创建一个新的 BroadcastChannel 实例。命名它(在这种情况下,广播频道的名称是'sw-messages')并使用“postMessage”方法发送消息:

      importScripts("https://js.pusher.com/beams/service-worker.js");
      const channel = new BroadcastChannel('sw-messages');
      
      PusherPushNotifications.onNotificationReceived = ({ pushEvent, payload }) => {
        pushEvent.waitUntil(
          self.registration.showNotification(payload.notification.title, {
            body: payload.notification.body,
            icon: payload.notification.icon,
            data: payload.data
          })
        );
        channel.postMessage({ title: payload.data});
      };

      在 vue 组件中,我(再次)创建一个新的 BroadcastChannel 实例,然后放置一个事件处理程序,如下所示:

      const channel = new BroadcastChannel("sw-messages");
          channel.onmessage = function (event) {
            this.pushNotification = event.data;
            console.log(this.pushNotification.title);
          }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-13
        • 1970-01-01
        • 2020-01-23
        相关资源
        最近更新 更多