此演示中显示了将工作人员的响应发送回受控应用程序的一种方法,并按以下方式完成(我还没有实际测试过,但演示运行良好,代码似乎与规范一致) .
在主页中:
function sendMessage(message) {
// 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) {
var messageChannel = new MessageChannel();
messageChannel.port1.onmessage = function(event) {
if (event.data.error) {
reject(event.data.error);
} else {
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(message, [messageChannel.port2]);
});
}
在服务工作者代码中:
self.addEventListener('message', function(event) {
event.ports[0].postMessage({'test': 'This is my response.'});
});
然后,您应该能够使用该sendMessage
函数返回的承诺,对来自服务工作者的响应执行您想要的操作。