Change iframe height with external src depending on content height

Asked

Viewed 2,268 times

3

I have an iframe where src points to an external domain

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

Since iframe has an external src, I cannot manipulate its contents to get the correct height.

How to change the height of the iframe?

  • Take a look here: http://stackoverflow.com/questions/5908676/yet-another-cross-domain-iframe-resize-qa

2 answers

0


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

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

Inside the iframe is an event that awaits the message. When the message is received iframe responds (also through "postMessage") with the height of its contents.

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

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 inside 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.

0

Take this example:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<head>
  <meta charset="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>
  <script type="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: https://github.com/davidjbradshaw/iframe-resizer

  • I tried, but since it is an iframe that is in another domain, I do not have permissions to access the "contentWindow" of iframe.

  • Look now. I updated.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.