0

I want to get the value of the TAG which "id" is "token" from the iframe (id: 'myFrame'), but i get a "null" value displayed.

I guess the problem is that the iframe is not loaded before the javascript get executed but i don't know how to solve this problem.

Thanks

<!DOCTYPE html>

<html>

<head>

    <title>Smth</title>

</head>


<body>

    <iframe src="script.php" name="myFrame" id="myFrame"></iframe>

    <script>

        var iframe = document.getElementById('myFrame'); 

        var innerDoc = iframe.contentDocument || iframe.contentWindow.document;

        document.write(innerDoc.getElementById("token").value);
    </script>


</body>

</html>
mric750
  • 183
  • 8
  • 1
    Possible duplicate of [How to check if iframe is loaded or it has a content?](http://stackoverflow.com/questions/9249680/how-to-check-if-iframe-is-loaded-or-it-has-a-content) – Davor Mlinaric Feb 26 '16 at 14:17

2 Answers2

0
<script>
    setInterval(function(){
         var iframe = document.getElementById('myFrame'); 

         var innerDoc = iframe.contentDocument || iframe.contentWindow.document;

         document.write(innerDoc.getElementById("token").value);
     }, 5000);
</script>
Stivan
  • 1,128
  • 1
  • 15
  • 24
  • Another solution would be is to use the on-load function. see this solution.http://stackoverflow.com/questions/29233928/iframe-onload-javascript-event – Stivan Feb 26 '16 at 14:25
0

What I would do, if I need to do it, is to add an onload event to the iframe so when it's loaded, execute the scripts you want to. For example:

document.body.onload = function(){
    document.getElementById('myFrame').onload = function(){ 
        /* your code */ 
    }
}

What I do to avoid this kind of problems is to append the calls to my JS functions at the end of the body, so I won't try to reference a DOM element before creating it (the functions are appended in the head element).

gabriel garcia
  • 368
  • 3
  • 17