Iframe跨域通信

很多情况下需要用到iframe嵌入子页面以达到也无需求,通常使用场景都是跨页面的情况下,这时候如果需要传递数据怎么处理呢?

父页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//  iframe页面
<iframe id="siri_child" src="<%=url%>" onload="postMsg()" width="100%"></iframe>
<script type="text/javascript">
var url="<%=url%>";
function postMsg(){
var msg = {sendMsg:'sendMsg',action:'registerChildFunc',setParentHeigh:'setParentHeigh'}
document.getElementById('siri_child').contentWindow.postMessage(msg, url)
}
window.addEventListener("message",function(obj){
var data = obj.data;
var action = data.action;
console.log(obj);
});
</script>

子页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//子页面
window.sendMsg = '';
window.setParentHeigh=0;
window.origin='';
window.addEventListener('message',function(event){
if(window.parent !== event.source){return}
if(event.data.action=='registerChildFunc'){
window.sendMsg=event.data.sendMsg;
window.setParentHeigh=event.data.setParentHeigh;
window.origin=event.origin;
}
}, false);

function send(userId){
if(window.sendMsg){
var msg = {userId,action:'sendMsg'}
parent.postMessage(msg, window.origin)
}
}

好吧,看起来很清晰,就不细说了