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.
Replace
attachEventinstead of theonunloadsetter to add the event. I’ve tested it in IE6 – 8, and it works fine. Make sure that you also useaddEventListenerfor IE9+ and other browsers: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
setIntervalorsetTimeoutto poll for the value of the boolean propertychildWindow.closed. It’s true when the window has been closed.For example:
Note: Other answers suggested to use the
beforeunloadevent. Keep in mind that the specification allows implementations to ignoreconfirm,alert,promptandshowModalDialogcalls during this event.