瀏覽器中兩個無關tab頁之間的通訊,一直都是比較經典的問題。下面就使用一種比較簡單的方法,利用storage 和 message 的事件分發 和 事件監聽來完成通訊。html
兩個tab頁面之間要進行通訊,還要藉助iframe進行中轉消息,讓本來連個無關的頁面 tabA 和 tabB 進行消息的發送。post
iframeA 嵌入到 tabA 中,其src 指向 bridge.html, 而後 tabB 頁面也嵌入iframeB ,src 也指向bridge.html,code
tabB 發送消息postMessage 到iframeB,在tabB中能夠經過iframeB.contentWindow 來獲取iframeB 中的window 對象;在iframeB中觸發message 事件後,完成與iframeA進行通訊,
而後iframeA以一樣的方式發送給tabA,完成一次頁面通訊。htm
tabB ----》 iframeB -----》iframeA ----》tabA;對象
tabB.html: <iframe id="bridge" src="./bridge.html"></iframe> <script> window.addEventListener('message',function(e){ let {data} = e; if(!data) return; let info = JSON.parse(JSON.parse(data)); document.querySelector('#bridge').contentWindow.postMessage(JSON.stringify({ data:"from tabB" }),"*"); }); document.querySelector('button').addEventListener('click',function(){ console.log('send message ....') document.querySelector('#bridge').contentWindow.postMessage(JSON.stringify({ data:"from tabB" }),'*') }) </script>
tabA.html <iframe id="bridge" src="./bridge.html" width="" height=""></iframe> <script> window.sendMessageToTab = function(data){ document.querySelector("#bridge").contentWindow.postMessage(JSON.stringify(data),'/'); } window.addEventListener('message',function(e){ let {data} = e; if(!data) return; let info = JSON.parse(JSON.parse(data)); console.log("BSay:",info); }); sendMessageToTab({ data:"hello world: B" }) </script>
bridge.html <script> window.addEventListener('storage',function(ev){ if(ev.key == "message"){ window.parent.postMessage(ev.newValue,'*') } }); function message_broadcast(message){ localStorage.setItem('message',JSON.stringify(message)); localStorage.removeItem('message'); }; window.addEventListener('message',function(e){ let {data} = e; // 接受到了父文檔的消息後,廣播給其餘的同源頁面 message_broadcast(data); }) </script>