https://developer.mozilla.org...html
在不使用webSocket和輪詢的狀況下,實現頁面之間的實時通訊web
使用SharedWorked能夠建立一個多頁面共享的進程,經過這種方式來實現多頁面之間的消息互通app
var portList = []; onconnect = function(e) { var port = e.ports[0]; portList.push(port); console.log(port) port.onmessage = function(e) { var workerResult = e.data; portList.map(item=>{ // item!=port&&item.postMessage(workerResult); /**不發給本身 */ item.postMessage(workerResult); /**發給本身 */ }); } }
這個文件在頁面中會被引用,用來建立一個共享進程對象。代碼中維護了一個鏈接對象池,定義了簡單的事件和方法。post
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div id="container"> </div> <input type="text" id="number3"> <button onclick="send()">send</button> </body> <script> var squareNumber = document.querySelector('#number3'); var container = document.querySelector('#container'); if (!!window.SharedWorker) { var myWorker = new SharedWorker("worker.js"); myWorker.port.onmessage = function(e) { console.log('Message received from worker' + e.data); var msgData = JSON.parse(e.data); var msg = `sender:${msgData.sender},content:${msgData.content}`; appendMessag(msg); } } function send() { var msgData = { sender:"index2", content:squareNumber.value } var msg = JSON.stringify(msgData); myWorker.port.postMessage(msg); } function appendMessag(msg){ var ele = document.createElement("p"); ele.innerHTML = msg; container.appendChild(ele); } </script> </html>
另外我還畫了一個簡單的模型圖,但願能幫助你加深理解ui