开发者

javascript passing event from one window to another

Is there any way to open a new window with,

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

and then pass events from newWindow to its opener window?

开发者_C百科What I want to do is open a window that asks for some information, then once it's been entered close the new window and trigger an action in the original window.

Thanks.

edit: Thanks all. That's pretty much how I thought it worked, but I must be doing something stupid. Here's some test code I've been banging my head against a wall over:

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();
});

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

I'd kind of like it to work the other way around too. Any way to make something like this work?

var child = window.open("child.html");

$(child).bind("something", function() { ... });

Thanks.


Yes, you can do this. In your new window, you can access the parent window by using window.opener This gives you access to all properties and function 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 like this in the new window.

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


I hesitate to plug jQuery unnecessarily, but it is quite nice for things like this:

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

Just run that line in the initialization script of the child window. Note: the even must obviously be bound to the body element in the parent.

Note that you are limited by single-origin policy here. Unless explicitly permitted by the browser, this will only work if both windows are opened from the same host.


Indeed it is possible, you want to look into window.addEventListener. This is usable in the modern browsers, as well as IE 9.

Visit this page for more information and examples.


window.opener.blah = "meh"

That sets a js var (blah) in the opener window to "meh"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜