iframe通信—postMessage

通常,对于两个不同页面的脚本,只有当执行它们的页面位于具有相同的协议(通常为 https),端口号(443 为 https 的默认值),以及两个页面的域名Document.domain设置为相同的值时,这两个脚本才能相互通信。window.postMessage() 方法提供了一种受控机制来规避此限制,可以实现跨源通信。

父页面url:http://10.9.0.89:8080/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div>
    <div>父页面</div>
    <iframe id="page1" src="http://10.9.0.89:8081/index.html" frameborder="0"></iframe>
  </div>
  <script lang="javascript">
    window.onload = function(){
      console.log("父页面加载成功");
      window.addEventListener("message", (event) =>{
        if(event.origin !== "http://10.9.0.89:8081")return;
        console.log("父页面接收到的数据", event.data);
      })
      // 向子页面发送消息
      document.getElementById("page1").contentWindow.postMessage({value: "parent"}, "http://10.9.0.89:8081")
    };
  </script>
</body>
</html>

子页面url:http://10.9.0.89:8081/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div>子页面</div>
  <script lang="javascript">
    window.onload = function(){
      console.log("子页面加载成功");
    };
    window.addEventListener("message", function(event) {
      if(event.origin !== "http://10.9.0.89:8080") return;
      console.log("页面1接收到数据", event.data);
      // 向父页面发送消息
      window.parent.postMessage({value: "son"}, 'http://10.9.0.89:8080')
    })
  </script>
</body>
</html>

postMessage() 参数具体使用方法参考:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值