- localStorage
- BroadcastChannel
- 回调方式
- message事件
- setinterval循环+sessionStorage
- websocket
localStorage
通过监听本地变量来实现
优点: 兼容性好,可适用于目前市面上大多数浏览器
缺点:需要考虑同源策略问题,同域名+同端口号
// a页面
window.addEventListener('storage', function (e) {
console.log(e)
// 去做一些其他的事
})
// b页面
localStorage.setItem('name', 1133)
BroadcastChannel
通过创建一个 BroadcastChannel 对象,并与对应的频道相关联
优点:支持在web worder中使用,可以传递数字,json等
缺点: 需要考虑同源策略问题,不支持ie
// a页面
var bc = new BroadcastChannel('gator_channel')
bc.onmessage = re => console.log(re)
// b页面
var bc = new BroadcastChannel('gator_channel')
bc.postMessage(213)
回调方式
通过window.opener方式实现
优点:可以直接访问到主页面的所有dom,bom以及全局变量方法等
缺点:容易发生安全性问题,如果跳到了不可靠的第三方地址会导致可以直接修改主页面的内容
opener 属性是一个可读可写的属性,可返回对创建该窗口的 Window 对象的引用。
当使用window.open()打开一个窗口,您可以使用此属性返回来自目标窗口源(父)窗口的详细信息。
// a页面
<button id="btn1">打开b</button>
<script>
function dialog() {
alert('a页面')
}
document.getElementById('btn1').addEventListener('click', function() {
window.open('./b.html', '_blank')
})
</script>
// b页面
<script>
window.opener.dialog();
</script>
message事件
通过postmessage实现
优点:可以算是上述方法的升级版,通过代码拓展修复上述方法的安全问题
缺点:同上述方法一样,容易出现安全性问题问题
// a页面
<button id="btn1">打开b</button>
<script>
function dialog() {
alert('a页面')
}
document.getElementById('btn1').addEventListener('click', function() {
window.open('./b.html', '_blank')
})
window?.addEventListener('message', event => {
// 过滤掉非同域名下的信息
if (event.origin === location.origin) {
console.log('安全')
}
console.log(event)
});
</script>
// b页面
<script>
window.opener.postMessage({age:14}, 'http://30.206.241.21:8081/b.html')
</script>
setinterval循环+sessionStorage
通过不断循环对比新旧值
优点:理论上兼容性最好
缺点:会造成大量不必要的资源浪费
// a页面
let oldValue = sessionStorage.getItem('name')
setInterval(() => {
const newValue = sessionStorage.getItem('name');
if (newValue != oldValue) {
console.log('发现新值')
}
}, 300)
// b页面
sessionStorage.setItem('name', 'tom');
websocket
与服务端结合通过网络实现信息互通
优点:不仅支持跨窗口,还支持跨浏览器跨设备跨系统
缺点:需要服务端支持,会造成服务端带宽的浪费
进阶: 不同源之间的沟通
利用iframe模式,在c页面(不同源)里新增一个iframe,src执行b.html,src里携带要传给a的参数,b.html里接收url参数之后,就可以利用上述的localStorage或者BroadcastChannel传给a.html
<script>
window.addEventListener('storage', function (e) {
console.log(e)
})
</script>
<script>
localStorage.setItem('name', location.search)
</script>
http://192.168.1.104:8080/c.html
<body>
<button id="bt1">给a.html发送消息</button>
<script>
document.getElementById('bt1').addEventListener('click', function() {
var ifrm = document.body.insertAdjacentHTML('beforeend', '<iframe src="http:/127.0.0.1:8080/b.html?r=1" />')
})
</script>
</body>