最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - window.unload in IE8 - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Feb 5, 2023 at 17:29 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Aug 3, 2012 at 12:08 TRRTRR 1,6433 gold badges26 silver badges43 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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.

You can try something with onbeforeunload. I use something like this on a print report for a intranet app that do an AJAX call to mark it was printed:

if (window.onbeforeunload) {
    window.onbeforeunload = function() { didPrint(someData); };
} else {
    window.onunload = function() { didPrint(someData); };
}
发布评论

评论列表(0)

  1. 暂无评论