There is one magic iframe with id="ifr" . The height of the contents of this iframe can take both 50px and 500px - depending on the screen extension. This is determined by the following method:

 document.getElementById('ifr').contentDocument.height 

In order for the iframe to select its height based on the internals itself, I wrote the following code:

 document.getElementById('ifr').style.height = document.getElementById('ifr').contentDocument.height + 'px'; 

I drive into the Chrome console - everything is ok.

Then I insert the code into the HTML page. It turned out like this:

 <iframe id="ifr" src="inpup.html"></iframe> <script type="text/javascript"> document.getElementById('ifr').style.height = document.getElementById('ifr').contentDocument.height + 'px'; </script> </iframe> 

The size of the iframe does not want to change.

Then I tried almost the same thing, only on onload :

 <body onload="document.getElementById('ifr').style.height = document.getElementById('ifr').contentDocument.height + 'px';"> 

Did not help.

Why does the code from the console work, and normally the code embedded in the page is not? How to fix it?

PS I need to embed the code in HTML. No need to force users to enter some incomprehensible line into some kind of obscure chrome console.

PPS Both the main page and iframe from one domain.

  • Somehow it is not very compatible that you want to change the width of the iframe and setting the value of height. You did not confuse? - Deonis
  • 3
    Because iframe is loaded later on the onload event. - KaZaca

1 answer 1

Move the code to onload . @ KaZatsa said everything correctly:

Because iframe is loaded later on the onload event.