简体   繁体   中英

How to get scroll height from iframe or outer div

I am trying to get the whole screen height until the scroll is happening (total height of content), here is the code which i tried but i am getting the value as 0 , for eg my guess is the whole screen height will be more then 1400px how to get the exact height

 <div id="sample">
     <iframe src="https://en.wikipedia.org/wiki/Main_Page" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0x;left:0px;right:0px;bottom:0px" height="100%" width="100%" allowfullscreen id="frame" onload="myFunction()">
     </iframe>
     <div style="display:block; clear:both;"></div>
 </div>


    <script>
    function myFunction() {
        var elmnt = document.getElementById("sample");
        var y = elmnt.scrollHeight;
        var x = elmnt.scrollWidth;
        var sample = "Height: " + y + "px<br>Width: " + x + "px";
        alert(sample);
    }
    </script>

You get height = 0 because the height of the iframe content is not related to the parent div element but to the iframe's document object, so you have to access the document object:

function myFunction() {
        var elmnt = document.getElementById("frame");
        var win = elmnt.contentWindow;
        var x = win.innerWidth;
        var y = win.innerHeight;
        var iframe = "Height: " + y + "px<br>Width: " + x + "px";
        alert(iframe);
}

But this doesn't work because of same-origin policy , and you will get the following error:

Error: Permission denied to access property "innerWidth"

Check MDN for more info on this error .

To access the DOM you have to parse a page using a headless browser like phantomjs (based on Node.js), this has to be done at server-side and it's a completely different approach, out of the scope of this question, but in case you want to try you can find lots of examples .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM