postMessage 实现跨源通信 iframe 跨域获取url

时间:2023-03-09 03:35:06
postMessage 实现跨源通信 iframe 跨域获取url

用postMessage实现跨源通信的方法实例

如:在www.bbb.com/index.html页面获取www.aaa.com/index.html的数据,以iframe的形式

www.aaa.com/index.html页面发送数据

<div  id="login_form">
<iframe id="login" onload = "onLoad" src="www.bbb.com/index.html" width="400px" height="650px" frameborder="no" scrolling="no"></iframe>
</div> function onLoad() {
var iframe = document.getElementById('login');
var win = iframe.contentWindow;
win.postMessage('{name:"ling",sex:"0"}','*')
}

www.bbb.com/index.html页面接收数据

window.onmessage = function (e) {
e = e || event;
if (e.origin !== 'https://captcha.luosimao.com bbb项目里用到的url但是项目aaa没有用到') {
console.log(e.data)
}
}