javascript - IE 不执行我的代码 'onunload'

标签 javascript jquery internet-explorer

我需要在离开浏览器之前执行一些代码,我实现了这个:

    window.onbeforeunload = function () { return 'Are you sure?'; };
    window.onunload = function () { releaseLocking(); };

它与 Google Chrome 配合得很好。关闭 GC 时:显示一条消息,

  • 如果我点击“留在页面上”按钮,什么也不会发生。完美。
  • 如果我点击“离开页面”按钮,releaseLocking下的代码将被执行。完美。

我在使用 Internet Explorer 时遇到问题。

  • 如果我点击“留在页面上”按钮,什么也不会发生。完美。
  • 如果我点击“离开页面”按钮,releaseLocking下的代码将不会被执行。

有什么想法吗?

我搜索了很多,但没有找到解决方案。

谢谢。

<小时/>

更新

var releaseLocking = function() {
    // Release only if lock is set on the current user
    if (transport().lockedById() == 5) { // 5 is dummy (Jean Dupont for testing)
        transport().lockedById(null);
        transport().lockedTime(null);
        return ctxTransport.saveChanges(SILENTSAVE);
    }
};

最佳答案

IE 似乎有一个错误,即卸载事件不会在网站的特定页面上触发。

卸载事件从未触发,因为页面的所有内容在导航到另一个页面之前尚未完成加载。

在卸载之前尝试停止它

试试这个:

function fixUnload() {
    // Is there things still loading, then fake the unload event
    if (document.readyState == 'interactive') {
        function stop() {
            // Prevent memory leak
            document.detachEvent('onstop', stop);

            // Call unload handler
            unload();
        };

        // Fire unload when the currently loading page is stopped
        document.attachEvent('onstop', stop);

        // Remove onstop listener after a while to prevent the unload function
        // to execute if the user presses cancel in an onbeforeunload
        // confirm dialog and then presses the stop button in the browser
        window.setTimeout(function() {
            document.detachEvent('onstop', stop);
        }, 0);
    }
};

function unload() {
    alert('Unload event occured.');
};

window.attachEvent('onunload', unload);
window.attachEvent('onbeforeunload', fixUnload);

关于javascript - IE 不执行我的代码 'onunload',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17012974/

相关文章:

javascript - GMaps JS 地理编码 : Using/Passing Variables With Asynchronous Geocode Function?

jquery - 使用 jquery 获取自定义标签(包含冒号)值

internet-explorer - 在 Internet Explorer 中启用 SOCKS 4a/5

javascript - 如何防止javascript中的Client DOM XSS漏洞?

javascript - 无法使用 jquery 触发点击事件的操作

javascript - IE 中的框阴影与 Chrome 中的不同

javascript:使用数据uri显示xml流

javascript - 如何使用 react-native-snap-carousel 在 react native 中获取和传递事件幻灯片的详细信息

javascript - 加载 jquery - 阻止 CDN 服务器往返

javascript - Ext.bind 在 ExtJS 中看不到函数