I have two windows: the parent
and the popup
. Obviously parent
has a reference to popup
. Now in popup
I have a function say
function test() { alert('test'); }
and I want to call this function in parent
, something like popup.test();
. Is there a way to do that? I do know how to do that the other way around. Just declaring
window.test = function() { alert('test'); }
and calling window.opener.test();
in popup works fine. However this does not work in my case (I think because the window.opener
object is a reference, but window.open
and window
in popup
are not really related). Any ideas?
It really depends on the context where you defined the function for the popup window. Assuming you attached the functions/data to the window
object of the popup window, you can access it from the window handle returned by window.open
(the window handle is the window
object for the popup):
var w = window.open(somelocation,''); //has a function on `window` called "test"
w.test();
I'm going to assume that you understand how security sandboxes work for popup windows
Declare test()
in your popup as follows:
window["test"] = function()
{
alert("It works!");
}
Then open your popup from your main window:
var popup = window.open("popup.html", "The popup");
And call your function:
popup.window.test();
jsFiddle (won't work without the /show
because of the cross-domain restriction!): http://jsfiddle.net/szK3F/show/
来源:https://stackoverflow.com/questions/8152829/run-function-from-child-window-in-parent-window