Guilherme Wunsch
Guilherme Wunsch

Reputation: 1

Get iframe content height in Google Chrome

can anyone help me to do this code works on Google Chrome? It work's perfectly on IE.

Thanks.

<!doctype html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
  <script>
    function calcIframeSize() {
      var altura = $("body", $("#frameExtraFields").contents()).height();
      $("#frameExtraFields").height(altura);
    }
    $(document).ready(function() {
      $("#frameExtraFields").ready( function() {
        calcIframeSize();
      });
    });
  </script>
</head>
<body>

<iframe src="frame.html" width="80%" height="600" id="frameExtraFields"></iframe>

</body>
</html>

Upvotes: 0

Views: 7135

Answers (2)

Amit Shah
Amit Shah

Reputation: 8199

Solution:

I do use the below code for all browser which specifically look for chrome:

The .offsetHeight returns same value in chrome compared with .scrollHeight in rest of the browsers.

var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);

if (document.getElementById) {
    newheight = isChrome 
    ? document.getElementById(id).contentWindow.document.body.offsetHeight 
    : document.getElementById(id).contentWindow.document.body.scrollHeight;
}

Complete function to resize the iframe height:

function autoResize(id) //id = iframe-id
{
    var newheight = 500;
    var newwidth;

    var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);

    if (document.getElementById) {
        newheight = isChrome ? document.getElementById(id).contentWindow.document.body.offsetHeight : document.getElementById(id).contentWindow.document.body.scrollHeight;

        newheightVisible = newheight + 30; //Don't ask me why this, i am also wondering but it works
    }

    if (newheight != lastheight) {
        jQuery("#" + id).css('height', newheightVisible);
        lastheight = newheightVisible;
    }
}

Upvotes: 1

Michel
Michel

Reputation: 28359

Considering that your iframe loads a src on the same domain, the following should do it :

<script>
    $(document).ready(function() {
        $('#frameExtraFields').load(function() {
            $(this).height($(this).contents().height());
        });
    });
</script>

<iframe src="/user/login/" width="80%" height="auto" id="frameExtraFields"></iframe>

Notice I removed the fixed height you set on the iframe element and setted it to auto instead.

See this fiddle

Upvotes: 2

Related Questions