iframe与父页面之间通讯跨域问题(from accessing a cross-origin frame.at HTMLIFrameElement.iframe.onload)

当我们想通过iframe中的内容自动改变iframe的高度时可能会想到使用load方法获取到iframe页面中的高度:

<iframe 
    name="web" width="100%" frameborder=0 height="0" 
    src="http:xxx.com" id="web" onload="this.height=web.document.body.scrollHeight">
</iframe>

这种方法在不跨域的情况下是可以的,但是涉及到跨域的话会出现这样的一个报错:

Uncaught DOMException: Blocked a frame with origin "http://localhost:XXX" from accessing a cross-origin frame.
    at HTMLIFrameElement.iframe.onload (http://localhost:XX/web/auth/:xx:xx)

上网查阅了很多资料介绍使用window.postMessage()方法,

/*test1.html 这是父页面 127.0.0.1:8080*/
<div>这是父页面</div>
<iframe name="web" width="100%" 
    frameborder=0 height="0"
    scrolling="no"
    src="http://172.16.1.17:8080/test2.html" 
    id="web">       
 </iframe>

 <script>
    window.onload = function() {
        var iframe = document.getElementById('web'); 
        iframe.contentWindow.postMessage("hello", "http://172.16.1.17:8080"); //将hello传递到iframe中

        function receiveMessage(event){

        if (event.origin !== "http://172.16.1.17:8080")
          return;
        
          console.log(event)

          iframe.setAttribute("height",event.data);
        }
       window.addEventListener("message", receiveMessage, false); //获取iframe传来的信息
    }
 </script>
/*test2.html 这是iframe页面 172.16.1.17*/
<div>这是iframe</div>

<script>
    window.onload = function(){
      var height = document.body.scrollHeight+20;
      function receiveMessage(
        
        if (event.origin !== "http://127.0.0.1:8080")
          return;

        event.source.postMessage(height,event.origin);//设置向父页面传递的值
        
        console.log(event);
      }

      window.addEventListener("message", receiveMessage, false);

    }
</script>

其实看这个demo挺简单,但是这里有几个需要注意的坑

  1. text2.html在浏览器打开后是没法成功,在这里我卡了很长时间
  2. 两个页面之间存在联系(一般是父子关系),不能在浏览器中直接输入两个页面的地址,a链接跳转也是不行的
  3. 别人的经验(推荐) https://github.com/Monine/monine.github.io/issues/2
  4. MDN介绍postMessage https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刺心疯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值