如何访问Redux存储在服务工作者上

时间:2017-06-28 21:21:48

标签: reactjs redux service-worker

我在我的应用程序中使用React,Redux和服务工作者,我想访问我的服务工作者的Redux商店。

我的服务人员是:

function checkCompatibility() {
  if ('serviceWorker' in navigator && 'PushManager' in window) {
    console.log('Service Worker and Push is supported');

    navigator.serviceWorker.register('./sw.js')
    .then(function (swReg) {
      console.log('Service Worker is registered', swReg);
    })
    .catch(function (error) {
      console.error('Service Worker Error', error);
    });
  } else {
    console.warn('Push messaging is not supported');
  }
}

function askForNotification() {
  if (!('Notification' in window)) {
    console.log('This browser does not support desktop notification');
  } else if (Notification.permission === 'granted') {
    console.log('Permission granted.');
  } else if (Notification.permission !== 'denied' || Notification.permission === 'default') {
    Notification.requestPermission(function (permission) {
      if (permission === 'granted') {
        var notification = new Notification('Permissão de Notificação foi Aceita', { icon: '/favicon.png', badge: '/favicon.png' });
      }
    });
  }
}

checkCompatibility();
askForNotification();

任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:2)

Service Worker构建于Web Worker API之上。根据{{​​3}}:

  

工作人员在另一个与当前窗口不同的全局上下文中运行

因此,服务工作者与Redux代码的范围不同。

但是,您可以使用MDN documentation on Web Workers API在主应用程序代码和服务工作者之间进行通信,并通过此渠道从Redux传递您需要的任何数据。

请查看代码示例postMessage以获取灵感。

答案 1 :(得分:1)

Service Worker 无法直接与 redux 存储通信。解决方法是让它与您的客户端通信并使用来自客户端的 redux 存储。 您可以使用广播频道来做到这一点。

// From service-worker.js:
const channel = new BroadcastChannel('sw-messages');
channel.postMessage({msg: 'Hello from SW'});

// From your client pages:
const channel = new BroadcastChannel('sw-messages');
channel.addEventListener('message', event => {
  console.log('Received', event.data);
});

答案 2 :(得分:0)

我发现Push.js解决了我的问题。

您可以导入并使用它来发送推送通知。

使用

安装
  

npm install --save push.js

import push from 'push.js'

push.create('Hello World!', {
    body: `${your-react-or-redux-var}`,
});
相关问题