message - Chrome ServiceWorker postMessage -
try postmessage between webapp , corresponding serviceworker. servicewoker registered , working far.
unfortunately noticed strange behavior:
1. navigator.serviceworker.controller null.
2. @ serviceworker side implemented postmessage way:
self.addeventlistener('message', function (evt) { console.log('postmessage received', evt); });
unfortunately important field post origin evt.origin=““ , evt.source=null not contain desired values. receive sent evt.data.
do know how post back?
thank much!
andi
one way send response worker controlled app shown in this demo , done following way (i haven't tested yet, demo works , code seems agree specs).
in main page:
function sendmessage(message) { // wraps message posting/response in promise, // resolve if response doesn't contain error, , reject // error if does. if you'd prefer, it's possible call // controller.postmessage() , set onmessage handler // independently of promise, 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); } }; // sends message data transferring // messagechannel.port2 service worker. // service worker can use transferred port reply // via postmessage(), in turn trigger onmessage // handler on messagechannel.port1. // see // https://html.spec.whatwg.org/multipage/workers.html#dom-worker-postmessage navigator.serviceworker.controller.postmessage(message, [messagechannel.port2]); }); }
and in service worker code:
self.addeventlistener('message', function(event) { event.ports[0].postmessage({'test': 'this response.'}); });
you should able use promise returned sendmessage
function want response coming service worker.
Comments
Post a Comment