0

I have a simple HTML code like this:

<!DOCTYPE html>
<html>
   </head>
   <script>
         function func() {
            var x = document.getElementById("frm").contentWindow.document;
            document.getElementById("val").innerHTML = "scrollHeight is: " + x.documentElement.scrollHeight;
        }
    </script>
   </head>
   <body>
        <button id="val" onclick="func()">getScrollHeight</button>
        <br>
        <br>
        <iframe id="frm" src="https://www.wikipedia.org/" width="100%"></iframe>
   </body>
</html>

I have a problem with above code:

When I clear the "src" attribute of IFrame(src="") and then click on the "getScrollHeight" button, it shows a number(in my browser it shows 150. The value is not important), But when I fill out the "src" attribute with a web address(for example src="https://www.wikipedia.org/") and then click on the button, it shows nothing. Why does this happen? Why can't I get the scroll height when the IFrame has a content?

My browser is chrome (also edge).

Thanks for any suggestion.

abc def
  • 19
  • 4
  • 1
    I don't think you can interact via JS with a website on a domain you do not control. – evolutionxbox Sep 10 '21 at 14:07
  • @evolutionxbox I just want to get the content height when I load a webpage into an IFrame and my reference is "https://javascript.info/size-and-scroll-window". the web address is not important. – abc def Sep 10 '21 at 14:18
  • @abcdef the web address is important. Unless you control the domain in which the iframe is loaded from, JS will not allow you to interact with it (there are exceptions that are not relevant to this question). That would be a huge security issue. – disinfor Sep 10 '21 at 14:26
  • @disinfor So is there an alternative way to get the IFrame's scroll height when it is loaded with a webpage? – abc def Sep 10 '21 at 14:34
  • @disinfor In fact the web page is an internal page of my website. What do you mean about "control the domain"? – abc def Sep 10 '21 at 14:37
  • @abcdef https://stackoverflow.com/a/42983075/989920 – evolutionxbox Sep 10 '21 at 14:42
  • @abcdef if the iframe is loaded from your own website - then you control the domain. In your example you have an external domain (wikipedia) - so we assume the question is about interacting with an external domain iframe. You should update your question to mention the iframe is populated by a page on your site. – disinfor Sep 10 '21 at 14:42
  • @evolutionxbox & disinfor, Many thanks for your replies. Yes, when the IFrame is loaded with an internal web page in my domain, the code works. – abc def Sep 10 '21 at 15:04

0 Answers0