// a.html
const bc = new BroadcastChannel('AlienZHOU')
bc.onmessage = function (e) {
console.log('[BroadcastChannel] receive message:', e.data);
};
// b.html
const bc = new BroadcastChannel('AlienZHOU')
bc.postMessage('data');
// a.html
window.addEventListener('storage', function (e) {
console.log(e)
})
// b.html
localStorage.a = 1
<!-- a.html -->
<iframe name="myIframe" src="http://localhost:1000/2.html"></iframe>
<!-- b.html -->
<script>
console.log(window.name)
</script>
<!-- a.html -->
<iframe name="myIframe" src="http://localhost:1000/2.html"></iframe>
<script>
var frame = document.querySelector('iframe')
frame.onload= function(){//这是异步加载的iframe
frame.src += '#aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
}
</script>
<!-- b.html -->
<script>
window.onhashchange = function() {
console.log(window.location.hash)
}
</script>
<!-- a.html -->
<iframe name="myIframe" src="http://localhost:1000/2.html"></iframe>
<script>
var frame = document.querySelector('iframe')
frame.onload= function(){//这是异步加载的iframe
window.frames[0].postMessage('data from html1', '*');
}
</script>
<!-- b.html -->
<script>
indow.onmessage = function (e) {
console.log(e.data, '11')
}
</script>
使用iframe作为中间桥梁
- a页面和b页面都嵌套bridge.html为iframe
- a页面触发bridge的postmessage
- bridge接受到postmessage,通过BroadcastChannel广播给所有都嵌套了bridge的页面
- 其他所有bridge都接受到广播,就调用父页面的postMessage
- b页面通过postMessage监听到消息
<!-- a.html -->
<iframe src="http://127.0.0.1:8082/bridge.html" frameborder="0" name="1111"></iframe>
<script>
var frame = document.querySelector('iframe')
frame.onload = function(argument) {
window.frames[0].postMessage('a.html', '*');
}
window.onmessage = function (e) {
console.log('a.html onmessage', e.data)
}
</script>
<!-- b.html -->
<iframe src="http://127.0.0.1:8082/bridge.html" frameborder="0" name="1111"></iframe>
<script>
window.onmessage = function (e) {
console.log('a.html onmessage', e.data)
}
</script>
<!-- bridge.html -->
<iframe src="http://127.0.0.1:8082/bridge.html" frameborder="0" name="1111"></iframe>
<script>
const bc = new BroadcastChannel('AlienZHOU')
// 收到来自页面的消息后,在 iframe 间进行广播
window.addEventListener('message', function (e) {
console.log(e, 'bridge')
bc.postMessage(e.data);
});
bc.onmessage = function (e) {
window.parent.postMessage(e.data, '*');
}
</script>