Faito
Faito

Reputation: 833

iframe content height null in chrome

i'm using jQuery to change the size of an iframe dinamically based on it's content so it doesn't display scrollbars. The script is pretty simple and it's working fine in IE9 but nothing happens in chrome, i added a small "alert" only for debbuging and i found out the the var "cont_height" is not defined in chrome.

All the files are in my computer, including the pages loaded in the iframe so there should be no cross domain issues.

The debugging tools in chrome give me this error: "Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match".

Here is the code

<script type="text/javascript" src="../js/jquery-1.10.2.min.js"> </script>
        <script type="text/javascript">
            $(document).ready(function () {
                $('#mainframe').load(function () {
                    var cont_height = $(this).contents().height();
                    alert(cont_height);
                    $(this).height(cont_height);
                });
            });
        </script>

I tried with "$(window).load" instead of document ready but i don't think it's a timing issue, i'm not being able to access the data due to permissions or something. I'll really appreciate any hint you can give me. The solution con be in javascript also.

Upvotes: 1

Views: 2471

Answers (1)

teewuane
teewuane

Reputation: 5734

This is the best way I've found to resize the iframe based on it's content.

<script>
    function resizeMe(id) {

        var theFrame = document.getElementById(id);




        var theBody = (theFrame.contentWindow.document.body || theFrame.contentDocument.body)
        var newHeight = Math.max(theBody.scrollHeight, theBody.offsetHeight, theBody.clientHeight);

        theFrame.height = (newHeight + "px");

    }
</script>


<iframe id="helloworld" ... onload="resizeMe('helloworld')"></iframe>

You can have the iframe document call the parent document with parent.resizeMe('helloworld').

<body onload="parent.resizeMe('helloworld')">
...
</body>

or since you have jquery...

<body>
    ...
    ...
    <script>

        $(document).ready(function(){
            parent.resizeMe('helloworld');
        });
    </script>

</body>

Upvotes: 1

Related Questions