make iframe height dynamic based on content inside- JQUERY/Javascript

前端 未结 20 1976
情书的邮戳
情书的邮戳 2020-11-22 07:42

I am loading an aspx web page in an iframe. The content in the Iframe can be of more height than the iframe\'s height. The iframe should not have scroll bars.

I have

20条回答
  •  隐瞒了意图╮
    2020-11-22 08:17

    I found that the accepted answer didn't suffice, since X-FRAME-OPTIONS: Allow-From isn't supported in safari or chrome. Went with a different approach instead, found in a presentation given by Ben Vinegar from Disqus. The idea is to add an event listener to the parent window, and then inside the iframe, use window.postMessage to send an event to the parent telling it to do something (resize the iframe).

    So in the parent document, add an event listener:

    window.addEventListener('message', function(e) {
      var $iframe = jQuery("#myIframe");
      var eventName = e.data[0];
      var data = e.data[1];
      switch(eventName) {
        case 'setHeight':
          $iframe.height(data);
          break;
      }
    }, false);
    

    And inside the iframe, write a function to post the message:

    function resize() {
      var height = document.getElementsByTagName("html")[0].scrollHeight;
      window.parent.postMessage(["setHeight", height], "*"); 
    }
    

    Finally, inside the iframe, add an onLoad to the body tag to fire the resize function:

    
    

提交回复
热议问题