When we want to automatically change the height of an iframe from the contents of the iframe, we might want to use the load method to get the height of the iframe page:

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

This method works if it is not cross-domain, but cross-domain is involved and an error occurs:

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)
Copy the code

There’s a lot of online literature on using the window.postmessage () method,

/*test1.html this is the parent page 127.0.0.1:8080*/<div>This is the parent page</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"); // Pass hello to 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); // Get the message from iframe
    }
 </script>
Copy the code
/*test2.html This is the iframe page 172.16.1.17*/<div>This is the 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);// Sets the value to be passed to the parent page
        
        console.log(event);
      }

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

    }
</script>
Copy the code

It’s actually pretty easy to watch this demo, but there are a couple of pitfalls

  1. Text2.html doesn’t work when the browser opens, and I’m stuck here for a long time
  2. There is a connection between two pages (generally father-son relationship), you can not directly enter the address of two pages in the browser,a link jump is also not available
  3. Experience of others (recommended) github.com/Monine/moni…
  4. MDN Introduction postMessage developer.mozilla.org/zh-CN/docs/…