Search code examples
javascripthtmlwindow

Cannot get the innerHTML of a window.open()


HI I have some troubles when reading the text inside a window that I open with window.open() I hope you guys can help me, what I need is my parent window will read the <div> html value of my child window that the parent window called, I have this code but It doesn't works

Parent Window

<button onclick="buttonset()">Click me</button>
<script>
var myWindow ;
 function buttonset () {
         myWindow = window.open("pag1.html", "myWindow", "width=200,height=100");
    //myWindow.document.write("<div id='hola'>This is 'myWindow'</div>");
    alert(myWindow.document.getElementById("result").innerHTML);
    myWindow.close();
}
</script>

And this is my Child Window (pag1.html) code

    <body>

<div id="result">1</div>
<div id="msj">Correcto</div>

</body>

and when I run it says and just open new window but it doesn't show the message

Cannot read property 'innerHTML' of null


Solution

  • Use load event of opened window

    myWindow.onload = function() {
      // do stuff
    }