Change iframe height with external src depending on content height

3

I have an iframe where src points to an external domain

After the content is loaded, a portion is hidden because the iframe does not fit the content.

Since the iframe has an external src, I can not manipulate its content in order to get the correct height.

How do I change the height of the iframe?

    
asked by anonymous 13.01.2015 / 21:17

2 answers

0

The problem was solved using "postMessage", remembering that the problem arose because I tried to access the contents of an iframe where "src" did not point to the same domain.

Basically what the code below does is send a message to the iframe after being loaded (onload) using the "postMessage".

Within the iframe there is an event waiting for the message. When the message is received the iframe responds (also via "postMessage") to the height of its content.

In the parent element where the iframe was inserted, there is another event waiting for the message with the height of the content.

Script of the page where the iframe was inserted:

//Gerando o iframe
var iframe = document.createElement('iframe');
as_root.appendChild(iframe);
iframe.id = "as-root-iframe";
iframe.style.width = '100%';
iframe.style.border = 'none';
iframe.style.scrolling = 'no';
iframe.style.overflow = 'hidden';
iframe.onload = function() {
    cpframe = document.getElementById('as-root-iframe').contentWindow;
    cpframe.postMessage('iframe-ok','*');
}
iframe.src = "http://dominio.como/embed/DYaok87sd";

//evento que aguarda a mensagem com a altura do conteúdo e posteriormente altera a altura do iframe
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
    document.getElementById('as-root-iframe').style.height = e.data+'px';
},false);

Script within the iframe:

//evento que aguarda mensagem do elemento "pai" solicitando a altura do conteúdo
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
var h = document.getElementById('as_content').offsetHeight+50;
    window.parent.postMessage(h,"*");
},false);

It was necessary to do everything with pure Javascript because it was not possible to use frameworks like Jquery.

    
14.01.2015 / 13:19
0

See this example:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><html><head><metacharset="utf-8">
  <title>iFrame message passing test</title>
  <meta name="description" content="iFrame message passing test">
  <meta name="viewport" content="width=device-width">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <script type="text/javascript">
    //MDN PolyFil for IE8 (This is not needed if you use the jQuery version)
    if (!Array.prototype.forEach) {
      Array.prototype.forEach = function(fun /*, thisArg */ ) {
        "use strict";
        if (this === void 0 || this === null || typeof fun !== "function") throw new TypeError();

        var
          t = Object(this),
          len = t.length >>> 0,
          thisArg = arguments.length >= 2 ? arguments[1] : void 0;

        for (var i = 0; i < len; i++)
          if (i in t)
            fun.call(thisArg, t[i], i, t);
      };
    }
  </script>
  <style type="text/css"></style>
</head>

<body>
  <h2>Automagically resizing iFrame</h2>
  <p>Resize window or click one of the links in the iFrame to watch it resize.</p>
  <div style="margin:20px;">
    <iframe src="http://davidjbradshaw.com/iframe-resizer/example/frame.content.html"width="100%" scrolling="no" id="iFrameResizer0" style="overflow: hidden; height: 334px;"></iframe>
  </div>
  <p id="callback"><b>Frame ID:</b> iFrameResizer0 <b>Height:</b> 334 <b>Width:</b> 1287 <b>Event type:</b> init</p>
  <div style="margin: 8px 0;font-size:13px;">
    For details on how this works, see
    <a href="http://davidjbradshaw.github.io/iframe-resizer/">http://davidjbradshaw.github.io/iframe-resizer/</a>.
  </div>

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script><scripttype="text/javascript" src="../js/iframeResizer.min.js"></script>
  <script type="text/javascript">
    iFrameResize({
      log: true, // Enable console logging
      enablePublicMethods: true, // Enable methods within iframe hosted page
      resizedCallback: function(messageData) { // Callback fn when resize is received
        $('p#callback').html(
          '<b>Frame ID:</b> ' + messageData.iframe.id +
          ' <b>Height:</b> ' + messageData.height +
          ' <b>Width:</b> ' + messageData.width +
          ' <b>Event type:</b> ' + messageData.type
        );
      },
      messageCallback: function(messageData) { // Callback fn when message is received
        $('p#callback').html(
          '<b>Frame ID:</b> ' + messageData.iframe.id +
          ' <b>Message:</b> ' + messageData.message
        );
        alert(messageData.message);
      },
      closedCallback: function(id) { // Callback fn when iFrame is closed
        $('p#callback').html(
          '<b>IFrame (</b>' + id +
          '<b>) removed from page.</b>'
        );
      }
    });
  </script>


</body>

</html>

<!-- begin snippet: js hide: false -->

Source: link

    
13.01.2015 / 23:03