5

消息通道在 Shared Worker 中有效吗?我想在几个共享工作者之间创建某种通信,所以我从这里举了一个例子,把它改成这样:

$(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 和 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();
}

但是当我从worker1 发送消息时,我没有在worker2 中收到它。我做错了什么还是不可能做的?有没有其他方法可以在不向浏览器选项卡发布消息的情况下与两个共享工作人员进行通信?

4

0 回答 0