浏览器中两个无关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>