注意:使用Create-React-App模板...(在其中修改Service Worker)
我正在使用通信通道api将消息发送给服务工作者进行缓存。我使用xmlhttp请求,因为它具有进度API,因为获取需要不确定的加载程序afaik。
因此,在接收到就绪状态4和状态代码200的数据后,我将postMessage发送到SW。我在客户端登录,但是在服务程序中没有收到消息。
我正在本地开发,并使用Chrome扩展程序允许对SW和Build进行本地测试: https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb?hl=en
客户片段
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) {
const res = JSON.parse(this.responseText);
function sendMessage(msg){
console.log("SEND SW MESSAGE");
const msgChan = new MessageChannel();
// This wraps the message posting/response in a promise, which will resolve if the response doesn't
// contain an error, and reject with the error if it does. If you'd prefer, it's possible to call
// controller.postMessage() and set up the onmessage handler independently of a promise, but this is
// a convenient wrapper.
return new Promise(function(resolve, reject){
console.log("Promise Scope");
msgChan.port1.onmessage = function(event){
event.data.error ? reject(event.data.error) : resolve(event.data);
}
// This sends the message data as well as transferring messageChannel.port2 to the service worker.
// The service worker can then use the transferred port to reply via postMessage(), which
// will in turn trigger the onmessage handler on messageChannel.port1.
// See https://html.spec.whatwg.org/multipage/workers.html#dom-worker-postmessage
navigator.serviceWorker.controller.postMessage(msg, [msgChan.port2]);
});
}
sendMessage(res).then(function(){
console.log("SW MESSAGE SENT");
// Storing Quake Data
that.props.setQuakes(res[0]);
// Storing Three Data Obj - SSR Parsing and Creation
that.props.setThreeData(res[1]);
// Greenlight
that.props.setVizInitSuccess(true);
}).catch(function(err){
console.log("Error Caching Data: "+err);
});
} };
服务人员片段
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
// Set up a listener for messages posted from the service worker.
// The service worker is set to post a message to all its clients once it's run its activation
// handler and taken control of the page, so you should see this message event fire once.
// You can force it to fire again by visiting this page in an Incognito window.
navigator.serviceWorker.onmessage = function(event) {
console.log("SERVICE WORKER RECIEVED MESSAGE");
console.log(event);
event.ports[0].postMessage("SW Says Hello Back!");
if (event.data.requireData == true && 'caches' in window) {
// Check for cache'd data and load
// clients.matchAll().then(clients => {
// clients.forEach(client => {
// console.log(client);
// //send_message_to_client(client, msg).then(m => console.log("SW Received Message: "+m));
// })
// })
// caches.open('threeData').then(function(cache){
// console.log("SW Cache");
// console.log(cache)
// event.ports[0].postMessage(cache);
// });
} else {
// Cache Data
caches.open('threeData').then(function(cache){
cache.put('/data.json', new Response(event.data.json))
});
}
};
...
答案 0 :(得分:3)
navigator
是 WorkerNavigator 界面,而不是 Navigator 界面。
WorkerNavigator 是 Navigator 界面的子集,允许从Worker (在本例中为其Service worker)进行访问。 WorkerNavigator Reference。
因此,服务工作程序文件中的navigator
不包含serviceWorker
对象。因此,当您调用navigator.serviceWorker.onMessage
时会引发错误。
要从客户端接收消息,请使用 Service Worker文件中的self.addEventListener
。
self.addEventListener('message', event => {
console.log(`[Message] event: `, event.data);
});