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

671 阅读1分钟

当我们想通过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. 别人的经验(推荐) github.com/Monine/moni…
  4. MDN介绍postMessage developer.mozilla.org/zh-CN/docs/…