SharedWorker
uses Message Port to exchange messages with ParentWorker
.
var port = new SharedWorker('/worker.js').port;
port.onmessage = function(e){
console.log(e.data);
};
port.start();
port.postMessage("Hello Shared Worker. I'm Mr. Tab");
onconnect = function(e){
var port = e.ports[0];
port.onmessage = function(e){
console.log(e.data);
};
port.start();
port.postMessage("Hello Mr. Tab. I'm Shared Worker.");
};
What about Service Worker? Is there anything similar to SharedWorker
Port?
@Jaffa The Cake's answer is just a simple in and out messaging channel, not an exact equivalent of SharedWorker
Port. At this time, there is no built-in interface which is similar to SharedWorker
Port in ServiceWorker
. Message Channel API is mandatory. Here is the one.
var mc = new MessageChannel();
mc.port1.onmessage = function(e){
console.log(e.data);
};
var sw = navigator.serviceWorker;
sw.register('/sw.js',{scope : '/'}).then(function(){
console.log("Service Worker is successfully registered.");
}).catch(function(er){
console.log("Registration failed.");
});
sw.ready.then(function(reg){
reg.active.postMessage('',[mc.port2]); //initialise the messaging channel
mc.port1.postMessage("Hello Service Worker. I'm Mr. Tab.");
});
//equals to onconnect in Shared Worker
onmessage = function(e){
var port = e.ports[0];
port.onmessage = function(e){
console.log(e.data);
};
port.postMessage("Hello Mr. Tab. I'm Service Worker.");
};
Note: This code is tested on Chrome 43 Beta.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments