在开发过程中如果有很多不同业务的情况下,会存在几个独立域名的情况,这样的话很多时候就需要在不同页面上共享一些数据来实现系统之间的关联。比如经常说到的单点登录。
对于存在不同域名的系统,可以借助iframe的src属性解决跨域数据不共享的问题,
然后用iframe的dom元素的contentWindow的postMessage向iframe内嵌的网页传递数据,
再在被内嵌的网页的代码中添加message事件截取消息,然后去保存token。具体代码见下方
点击跳转的回调函数:
toNewPage(){
//获取目标系统的登录证据token
...
const iframe = document.createElement('iframe')
//设置iframe样式,使其不可见
iframe.setAttribute(
'style',
'position:absolute;width:0px;height:0px;left:-500px;top:-500px;'
)
iframe.setAttribute(
'allow',
'payment'
)
//将iframe地址改为目标系统
iframe.src='http://127.0.0.1:8010/'
document.body.append(iframe)
iframe.onload = () => {
//发送消息,'http://127.0.0.1:8010'为目标系统网址,可改为‘*’
iframe.contentWindow.postMessage({token:'***'},'http://127.0.0.1:8010')
setTimeout(function () {
iframe.remove()
}, 5000)
//新开页签,跳转到目标系统地址
setTimeout(function () {
window.open('http://127.0.0.1:8010/', '_blank')
}, 0)
}
}
需要实现免登录的子系统,可在index.html中添加:
<script>
window.addEventListener('message',event => {
const origin = [
'http://localhost:8080',
'http://127.0.0.1:8080',
...
]
if(origin.includes(event.origin)){
console.log(event)
window.localStorage.setItem('cookie', event.data.tooken)
}
})
</script>
该方法只验证了点击按钮后,跳转到系统B,并且在localStorage中有了cookie记录,
这只是自己实现的小demo没有实际用过的,有需要的小伙伴可以实现一下