window.opener is null - I'm trying to alert a variable (from the parent window) in my child window - Javascript

StackOverflow https://stackoverflow.com/questions/23597761

Question

I'm trying to alert a variable (from the parent window) in the child window. I've looked at solutions on here but they don't work for me and I assume there's something missing or wrong in my code. When I run the code, the error console tells me that the window.opener is null. I've tried parent.window.opener... and that also says the same thing.

parent.htm:

<head>
<script type="text/javascript">
            var testtest = "hi";

            function reply_click(clicked_id){

                document.getElementById('resultspanel').style.display = 'none';
                document.getElementById('mainpanel').style.display = 'none';            

                var buttonid = clicked_id;
                window.buttonid = buttonid; //makes it global
                alert(buttonid);

                switch(clicked_id) {
                    case "1":
                    case "2":
                    case "3":
                    case "4":
                    case "5":
                    case "6":
                    case "7":
                    case "8":                   
                    case "9":
                    case "10": $('#mainpanel').load("info.htm");document.getElementById('mainpanel').style.display = 'block'; break;    
                }

                    //$('#mydiv').load('newPage.html', {field1: 'value1', ...});
            }


            </script>
</head>

child.htm

<head>
<script type="text/javascript">
            function test(){
                //alert(this.parentNode.id);
                //alert(parent.window.opener.testtest);
                //window.opener.alert(testtest);
                var myvar = window.opener.buttonid;
                alert(myvar);
            }
        </script>
</head>
    <body>      
    <p>INFORMATION</p>
        <div id = "test" style = "border-style:solid; height:10%; width:10%;" onClick = "test();" >DIV</div>
    </body>
Was it helpful?

Solution

You were correct to some extent. window.opener is a reference to the window, which opened current one. But this is applied only for windows called with window.open function. And they're usually appear in new window (or tab).

If one needs to address different frames, then he should use parent property for direct ancestor, top for the topmost frame and frames property for direct children. There're additional complications, when you use frameset instead of iframes (like window with frameset don't have direct content). I hope you won't need them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top