How to get height of iframe cross domain

帅比萌擦擦* 提交于 2019-12-23 09:36:39

问题


I have iframe(cross domain) with src from facebook, twitter or etc. I need to get height of iframe but i got issue: "Permission denied to access property 'document'". Please help me to resolve this. Many thanks!


回答1:


Couple issues. First, the height of the iframe is likely not what you want. I mean that's set explicitly in the HTML code of the page you control and is readily accessible and modifiable through any Javascript means. What it appears you are after is the height of the page inside the iframe. If that's the case, the simple answer is you can't, at least not with external services like Facebook/Twitter.

Due to security reasons, one can easily pass messages from child to parent, but not from parent to child, unless a communication pathway has been built into your javascript in both documents. There is a postMessage protocol for handling this in modern browsers. https://developer.mozilla.org/en/DOM/window.postMessage . But, it's wholly useless in this case unless the document you are communicating with is setup to handle an incoming postMessage, which to my knowledge Twitter/Facebook frequently are not.

If a parent document could freely communicate with children from different domains, then any javascript could effectively execute any series of commands on any site you're logged in as. The security implications of that are frightening and thankfully not possible.




回答2:


There is no options in javascript to find the height of a cross domain iframe height but you can done something like this with the help of some server side programming. I used PHP for this example

<?php
$output = file_get_contents('http://yourdomain.com');
?>
<div id='iframediv'>
    <?php echo $output; ?>
</div>

<iframe style='display:none' id='iframe' src="http://yourdomain.com" width="100%" marginwidth="0" height="100%" marginheight="0" align="top" scrolling="auto" frameborder="0" hspace="0" vspace="0"> </iframe>

<script>
if(window.attachEvent) {
    window.attachEvent('onload', iframeResizer);
} else {
    if(window.onload) {
        var curronload = window.onload;
        var newonload = function(evt) {
            curronload(evt);
            iframeResizer(evt);
        };
        window.onload = newonload;
    } else {
        window.onload = iframeResizer;
    }
}
   function iframeResizer(){
        var result = document.getElementById("iframediv").offsetHeight;

        document.getElementById("iframe").style.height = result;
        document.getElementById("iframediv").style.display = 'none';
        document.getElementById("iframe").style.display = 'inline';
    }
</script>


来源:https://stackoverflow.com/questions/8223239/how-to-get-height-of-iframe-cross-domain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!