问题描述:

Does Message Channel work in Shared Workers? I want to create some kind of communication between several Shared Workers, so I took example from here and change it into this:

$(function() {

var worker1 = new SharedWorker("worker1.js");

var worker2 = new SharedWorker("worker2.js");

var channel=new MessageChannel();

worker1.port.start();

worker2.port.start();

worker1.port.onmessage = function(e) {

$("#log").append("<br>" + e.data);

console.log(e.data);

}

worker1.port.postMessage({

code : "start",

msg : "ping"

},[channel.port1]);

worker2.port.onmessage = function(e) {

$("#log").append("<br>" + e.data);

console.log(e.data);

}

worker2.port.postMessage({

code : "start",

msg : "ping"

},[channel.port2]);

/*channel.port1.postMessage("channel port1 msg");

channel.port1.onmessage=function(e){

$("#log").append("<br> port1 recieved msg : " + e.data);

console.log(e.data);

}*/

$("#send1").click(function() {

var msg = $("#msg").val();

if (msg && msg != "start")

worker1.port.postMessage({

code : "msgw",

msg : "ping2"

});

$("#msg").val("");

})

$("#send2").click(function() {

var msg = $("#msg").val();

if (msg && msg != "start")

worker2.port.postMessage({

code : "msgw",

msg : "ping3"

});

$("#msg").val("");

})

$("#send3").click(function() {

var msg = $("#msg").val();

if (msg && msg != "start")

worker1.port.postMessage({

code : "msgch",

msg : "ping3"

});

$("#msg").val("");

});

$("#send4").click(function() {

var msg = $("#msg").val();

if (msg && msg != "start")

worker2.port.postMessage({

code : "msgch",

msg : "ping3"

});

$("#msg").val("");

})

});

worker1.js and worker2.js:

var channelPort;

function getChannelMessage(e){

postMessage(e.data+" >> channel recieved msg in worker1 ");

}

self.onconnect = function(e){

var port = e.ports[0];

port.onmessage = function(e) {

if (e.data.code == "start") {

channelPort = e.ports[0];

channelPort.start();

channelPort.postMessage(e.data.msg+" >> worker1 channel post");

channelPort.onmessage = getChannelMessage;

} else if(e.data.code=="msgw")

{

port.postMessage(e.data.msg+" >> worker1 got msg");

}else if(e.data.code=="msgch")

{

channelPort.postMessage(e.data.msg+" >> worker1 got msg");

}

};

port.start();

}

But when I send message from worker1 I don't receive it in worker2. Am I doing something wrong or is it impossible to do? Is there any other way of communicating two Shared Workers without posting message to browser tab?

相关阅读:
Top