localStorage
// 本窗口的设值代码
localStorage.setItem("EVENT.PUB", JSON.stringify({username : 'yiifaa', now : Date.now()}))
// 请务必注意,localStorage不能直接传送复合类型的值(对象)
// 其他窗口监听storage事件
$(window).on('storage', function(ev) {
var event = ev.originalEvent,
message = JSON.parse(event.newValue);// 解析出复合的对象值
// 对获取到的值进行处理
console.log(message)
})
postMessage
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>
websocket
// 中转服务器
var ws = new WebSocket("ws://www.example.com/socketserver");
ws.onopen = function (event) {
// 或者把此方法注册到其他事件中,即可与其他服务器通信
ws.send({username : 'yiifaa', now : Date.now()}); // 通过服务器中转消息
};
ws.onmessage = function (event) {
// 消费消息
console.log(event.data);
}