使用 iframe + postMessage 实现跨域通信

在实际项目开发中可能会碰到在 a.com 页面中嵌套 b.com 页面,这时第一反应是使用 iframe,但是产品又提出在 a.com 中操作,b.com 中进行显示,或者相反。

1、postMessage

  postMessage方法允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本档、多窗口、跨域消息传递。

语法:

otherWindow.postMessage(message, targetOrigin, [transfer]);
  • otherWindow:其他窗口的引用,如 iframe的contentWindow、执行window.open返回的窗口对象、或者是命名过或数值索引的window.frames。
  • message:将要发送到其他window的数据。
  • targetOrigin:指定那些窗口能接收到消息事件,其值可以是字符串 “*” 表示无限制,或者是一个URI。
  • transfer:是一串和message同时传递的Transferable对象,这些对象的所有权将被转移给消息的接收方,而发送方将不再保留所有权。

postMessage方法被调用时,会在所有页面脚本执行完毕之后像目标窗口派发一个 MessageEvent 消息,该MessageEvent消息有四个属性需要注意:

  • type:表示该message的类型
  • data:为 postMessage 的第一个参数
  • origin:表示调用postMessage方法窗口的源
  • source:记录调用postMessage方法的窗口对象

parent.html

<!DOCTYPE html> 
<html>
<head>
<meta charset="utf-8">
<title>iframe+postMessage 跨域通信 主页面</title>
</head>
<body>
    <h1>主页面</h1>
    <iframe id="child" src="./child.html"></iframe>
    <div>
        <h2>主页面接收消息区域</h2>
        <span id="message"></span>
    </div>
</body> 
<script>
    window.onload = function(){
        document.getElementById('child')
         .contentWindow.postMessage("主页面消息","http://192.168.23.10:9000/child.html")//父向子传递
    }
    window.addEventListener('message', function(event){//父获取子传递的消息
        document.getElementById('message').innerHTML = "收到"
         + event.origin + "消息:" + event.data;
    }, false)
</script>
</html>

  child.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>iframe+postMessage跨域通信 子页面</title>
</head>
<body>
    <h2>子页面</h2>
    <div>
        <h3>接收消息区域</h3>
        <span id="message"></span>
    </div>
</body>
<script>
    window.addEventListener('message',function(event){//子获取父消息
        console.log(event);
        document.getElementById('message').innerHTML = "收到" + event.origin + "消息:" + event.data;
        console.log(top)
        top.postMessage("子页面消息收到", 'http://192.168.23.10:9000/parent.html')//父向子消息
    }, false);
</script>
</html>

  注:不支持file协议

猜你喜欢

转载自www.cnblogs.com/yiyi17/p/9238829.html