我正在开发一个包含子应用程序的应用程序。我正在尝试使用共享工作者。一个共享工作器将用于 websockets,另一个用于每个子应用程序。
请帮助我在这两个共享工作者之间建立沟通。
我尝试使用 MessageChannel,但似乎它用于网络工作者。
<script>
var channel = new MessageChannel();
var worker1 = new SharedWorker('worker1.js');
var worker2 = new SharedWorker('worker2.js');
worker1.postMessage({
command: 'connect'
}, [channel.port1]);
worker2.postMessage({
command: 'connect'
}, [channel.port2]);
var sendMessage = function() {
var message = document.getElementById('test').value();
worker1.postMessage({
command: "forward",
message: message
});
}
</script>
工人 1 和 2
var otherWorker
var onMessageArrival = function(event) {
console.log("Received a message: " + event.data);
};
self.onmessage = function(event) {
switch (event.data.command) {
// Setup connection to worker 2
case "connect":
otherWorker = event.ports[0];
otherWorker.onmessage = onMessageArrival;
break;
// Forward messages to worker 2
case "forward":
// Forward messages to worker 2
otherWorker.postMessage(event.data.message);
break;
//handle other messages from main
default:
console.log(event.data);
}
};