本文介绍了使用“navigator.serviceWorker.controller.postMessage";它将始终“TypeError:无法读取 null 的属性 'postMessage'";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题是,在注册 Service Worker 后,navigator.serviceWorker.controller 总是 null.

I have the problem that after registering the service worker the navigator.serviceWorker.controller always is null.

我想使用 postMessage 向 Service Worker 发送消息.但是,navigator.serviceWorker.controller 总是返回 null,并显示错误 TypeError: Cannot read property 'postMessage' of null.

I want to use postMessage to send a message to the service worker.However, navigator.serviceWorker.controller always returns null,and shows the error TypeError: Cannot read property 'postMessage' of null.

有时我可以使用 navigator.serviceWorker.controller.postMessage,但在其他时候 navigator.serviceWorker.controller 返回 null,我不知道如何处理这个问题...

Sometimes I can use navigator.serviceWorker.controller.postMessage, but at other times navigator.serviceWorker.controller returns null,I am not sure how to deal with this issue...

我已经做了一些研究,但我仍然无法解决我的问题...

I have done some research, but I still cannot fix my issue...

有人有什么想法吗?

谢谢,特里

这是我创建的测试页面.https://terrylee7788.github.io/test_web_worker.html

Here is the test page that I created.https://terrylee7788.github.io/test_web_worker.html

推荐答案

使用 navigator.serviceWorker.ready

navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
  // Let's see if you have a subscription already
  return serviceWorkerRegistration.pushManager.getSubscription();
})
.then(function(subscription) {
  if (!subscription) {
    // You do not have subscription
  }
  // You have subscription.
  // Send data to service worker
  navigator.serviceWorker.controller.postMessage({'data': dataToServiceWorker});

})

这篇关于使用“navigator.serviceWorker.controller.postMessage";它将始终“TypeError:无法读取 null 的属性 'postMessage'";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 10:51