Search code examples
javascriptdom-events

window.unload in IE8


I want to execute a JavaScript on unload of a child window which was opened by the parent window. I tried the below code and it is not calling the function.

 childWindow = window.open(url, 'MyWindow', GetWindowOptions(1020, 600), true);
 childWindow.onunload = function () { test(); };

And the test function which I wrote is:

function test() {
alert(1);
}

I am using IE8 browser.


Solution

  • Replace attachEvent instead of the onunload setter to add the event. I've tested it in IE6 - 8, and it works fine. Make sure that you also use addEventListener for IE9+ and other browsers:

    var unloadFunc = function () { test(); };
    if (childWindow) { // null if a pop-up blocker does not create the window
        if (childWindow.addEventListener) {
            childWindow.addEventListener('unload', unloadFunc, false);
        } else {
            childWindow.attachEvent('onunload', unloadFunc);
        }
    }
    

    Obviously, this will not work if the URL is from a different domain.
    If you want to execute a function when a window from a different origin is closed, use setInterval or setTimeout to poll for the value of the boolean property childWindow.closed. It's true when the window has been closed.

    For example:

    if (childWindow) { // null if a pop-up blocker does not create the window
        setTimeout(function checkState() {
            if (childWindow.closed) {
                // onunload Logic here.
            } else {
                setTimeout(checkState, 250);
            }
        }, 250);
    }
    

    Note: Other answers suggested to use the beforeunload event. Keep in mind that the specification allows implementations to ignore confirm, alert, prompt and showModalDialog calls during this event.