首页 > 解决方案 > 如何将服务工作者中的事件接收到的数据导出到vue组件?

问题描述

我正在用 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);
};

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

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

服务工作者被放置在“公共”文件夹中。

我该怎么做?

标签: vue.jsservice-workerpusher

解决方案


服务工作者仅通过消息与页面通信。

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)
  }
}

推荐阅读