Search code examples
javascriptjquerywindow.openonunload

javascript/jquery open.window popup fires onunload after about:blank unloads


Let's say I have a button that opens a popup with window.open():

<button id = "my-button">Open window</button>​

And I want to capture when this window closes. I use the following code:

$('#my-button').on('click', function() {
    popup = window.open('http://www.google.com', 'my_popup', "width=800,height=600,scrollbars=no,resizable=yes,status=yes,toolbar=no,location=no,menubar=no");
    $(popup.document).ready(function() {
        console.log('ready!');
        $(popup).on('unload', function() {
            console.log('unloaded!');
        } );
    })    
});​

Now, I've noticed that the opened window briefly loads "about:blank" and then loads the requested url. At that time, the onunload event is fired. Other posts say that this is normal behavior, but I don't seem to get a 2nd onunload event (using chromium at least).

Anybody have a workaround to suggest?

See fiddle: http://jsfiddle.net/periklis/NJz6w/

As always, thanks in advance


Solution

  • ok I found a solution after all:

    $('#my-button').on('click', function() {
        popup = window.open('http://www.google.com', 'my_popup', "width=800,height=600,scrollbars=no,resizable=yes,status=yes,toolbar=no,location=no,menubar=no");
        $(popup.document).ready(function() {
            console.log('ready!');
            $(popup).on('unload', function() {
                console.log('unloaded!');
                $(popup).on('unload', function() {
                    console.log('unloaded 2nd time!');
                } );
            } );
        })    
    });​
    

    Which strangely works on my environment but not for the jsfiddle example I posted. Anyway.