替代jquery库来解析beforeunload/unload事件

izd*_*zdi 3 javascript jquery

编辑:因为我的问题似乎不清楚 - 我只想confirm()通过关闭浏览器/输入新链接/点击现有链接,每当用户离开页面时添加消息

我在读取/卸载事件之前已经阅读了很多相关的主题,但实际上没有一个能帮助我,可能是我做错了.

我通过单击所有链接来运行脚本,但是'beforeunload'事件在我的情况下不起作用

正常的脚本

$('a').on('mousedown', function(){
    var message = 'You are about to leave the page. Continue?'
    var result = confirm(message)
    if (result) {
        // some stuff
    } else {
        // some other stuff
    }
})
Run Code Online (Sandbox Code Playgroud)

尝试使用beforeunload

$(window).on('beforeunload', function(){
    var message = 'You are about to leave the page. Continue?'
    var result = confirm(message)
    if (result) {
        // some stuff
    } else {
        // some other stuff
    }
})
Run Code Online (Sandbox Code Playgroud)

什么也没发生.我也尝试过卸载事件,但仍然没有运气.

ast*_*tex 7

beforeunload事件有点奇怪.大多数浏览器不允许您从处理程序触发确认对话,因为这将允许站点不断弹出确认对话而不是导航离开页面.相反,您应该返回要显示的消息,例如:

$(window).on('beforeunload', function(e) {
    var msg = 'You are about to leave the page.  Continue?';
    (e || window.event).returnValue = msg;  //IE + Gecko
    return msg;  //Webkit
});
Run Code Online (Sandbox Code Playgroud)

如果要在结果对话框退出后运行其他javascript,请添加一个onunload侦听器.

编辑

正如评论中指出的那样,这些事件因浏览器而异.例如,最新版本的gecko(firefox)不允许自定义消息.