高级之路篇五:浏览器之通信

先说下,时下兼容性较好的,需求量较大的同浏览器同源打开的两个不同tab标签页的通信:

1、window.postMessage

适用情形:A页面中通过JavaScript的window.open打开B页面,或者B页面通过iframe嵌入至A页面

2、onstorage

适用情形:两个互不相关的通源tab页面通信

window.addEventListener("storage", function(e){
    ......
});

通过window对象侦听storage事件,会侦听localStorage对象的变化事件(包括item的添加、修改和删除)。

3、两个互不相关的tab页面通信。

我们巧妙的结合HTML5 postMessage API 和 storage事件实现这两个毫无关系的tab页面的连通。为此,我想到了iframe,通过在这两个tab页嵌入同一个iframe页实现“桥接”,最终完成通信:

tab A -----> iframe A[bridge.html]
                     |
                     |
                    \|/
             iframe B[bridge.html] ----->  tab B    

4、cookie + setInterval()

将要传递的信息存储在cookie中,每隔一定时间读取cookie信息,即可随时获取要传递的信息。

猜你喜欢

转载自blog.csdn.net/HuaiCheng9067/article/details/89515358