Javascript passing an event from one window to another

Is there a way to open a new window with

var newWindow = window.open(...); 

and then pass events from newWindow to its opening window?

I want to open a window in which some information is requested, after it is entered, close a new window and call the action in the original window.

Thanks.

edit: Thanks everyone. This is pretty much how I thought it worked, but I have to do something stupid. Here is some test code that I hit my head against the wall:

in parent.html

 window.open("child.html"); $(window).bind("something", function(e) { console.log('something happened'); }); 

and in child.html

 $("#somebutton").click(function() { $(window.opener).trigger("something"); window.close(); }); 

the child opens normally, I press the button, and the child closes, but "something" never happens in the parent !?

I would like it to be the other way around. Any way to do something like this work?

 var child = window.open("child.html"); $(child).bind("something", function() { ... }); 

Thanks.

+4
source share
4 answers

I hesitate to include jQuery unnecessarily, but this is pretty good for things like this:

 $('#somebutton').click(function() { window.opener.$('body').trigger('someevent', somedata); }); 

Just run this line in the initialization script of the child window. Note: even must be necessarily associated with the body element in the parent.

Please note that you are limited to a single origin policy. Unless explicitly permitted by the browser, this will only work if both windows open from the same host.

+5
source

Yes you can do it. In a new window, you can access the parent window using window.opener . This gives you access to all the properties and functions of the parent window, so you can do things like this, for example: window.opener.someFunctionOfMainWindow('some data from new window');

In your case, you can do something similar in a new window.

 function dataIsEntered() { window.opener.triggerAction(data); window.close(); } 
+4
source

In fact, perhaps you want to look into window.addEventListener . This can be used in modern browsers, as well as in IE 9.

Visit this page for more information and examples.

+1
source
 window.opener.blah = "meh" 

This sets js var (blah) in the opening window in "meh"

0
source

All Articles