views:

64

answers:

2

Hi,

I'm trying to do this:

$(function() {
    var parent = window.opener;

    $(window).bind('unload', function() {
        parent.setTimeout(function() {
            parent.console.log('Fired!');
        }, 200);
    }
});

The example above works well in FF, Chrome etc. but not IE8. In the latter, the callback specified in setTimeout() never seems to be fired.

Rationale is that I would like to execute some code in the parent window (window.opener), when a popup window is closed. I would like the popup to be responsible for this, and not the other way around.

Just to show that the concept works:

$(function() {
    var parent = window.opener;

    $(window).bind('unload', function() {
        parent.console.log('Fired!');
    }
});

Calling console.log immediately in the callback bound to unload (as in the example above) seems to be working in all browsers (not targeting IE6 here), but as soon as I add setTimeout() to the mix it breaks.

Is it possible? Is it a scope issue?

A: 

Try this:

var ex = function(){
    console.log('fired');
};

setTimeout.apply(parent, [ex, 2000]);

If that does not work, maybe this will:

if(parent.contentWindow)
   parent.contentWindow.console.log('Fired!');
jAndy
+1  A: 

In IE, functions are bound to their owner window. They can be called from another window, but when a window is unloaded, all its functions die. If you try to call one explicitly after onunload, you'll get a ‘The object invoked has disconnected from its clients’ error.

So in the child onunload you should call the parent back immediately. If the parent needs a delay, it'll have to provide it itself.

(You should probably also check that the parent is not null, hasn't been closed, and wrap the access attempt in a try, so that you don't get an error if the parent window has been closed or navigated.)

bobince
Aww bummer. Guesss I have to try a different approach then.Any chance it's possible to pass a callback function from the 'child' to it's parent? Comments are probably not a great place for code, but I'm thinking something along the lines: parent.$(parent).trigger('myEvent', {'callback': function() {alert('foo');});I've tried the above and the callback also seems to be bound to the child window. Any chance there is a solution to that?
peterfarsinsen