Search code examples
javascriptwindow.opener

JavaScript window.opener call parent function


I am trying to call a javascript function defined in a parent from a child window. I have two files like this:

Parent:

<html>
<head>
<title>Test</title>
<script type="text/javascript">
function foo () {
alert ("Hello from parent!");
}
function doStuff () {
var w = window.open("testa.html");
}
</script>
</head>
<body>
<input type="button" value="open" onClick="doStuff();" />
</body>
</html>

And child:

<html>
<head>
<title>Test A</title>
<script type="text/javascript">
function get() {
window.opener.foo();
}
</script>
</head>
<body>
<input type="button" value="Call Parent" onClick="get();" />
</body>
</html>

I can not, for the life of me, call the function foo from the child process. I thought this should be possible with the window.opener object, but I can not seem to make this work. Any suggestions?


Solution

  • Ensure you are accessing this via http:// so the Same origin policy passes and you can access opener from the child. It won't work if you're just using file://.