简体   繁体   English

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

[英]alternative jquery library to triger beforeunload/unload event

edit : As my question seems unclear - all i want is to add confirm() message whenever the user leaves the page by closing browser/typing new link/clicking existing link 编辑 :因为我的问题似乎不清楚 - 所有我想要的是每当用户离开页面时通过关闭浏览器/键入新链接/单击现有链接添加confirm()消息

I've read a lot of topics concerned beforeunload/unload events, but none of those actually could helped me, may be i'm doing smth wrong. 我在读取/卸载事件之前已经阅读了很多相关的主题,但实际上没有一个能帮助我,可能是我做错了。

I have the script working by clicking all the links, however 'beforeunload' event does not work in my situation 我通过单击所有链接来运行脚本,但是'beforeunload'事件在我的情况下不起作用

normal script 正常的脚本

$('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
    }
})

trying with beforeunload 尝试使用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
    }
})

And nothing is happening. 什么也没发生。 I've tried unload event too, but still no luck. 我也尝试过卸载事件,但仍然没有运气。

beforeunload events are a little odd. beforeunload事件有点奇怪。 Most browsers won't allow you to trigger a confirm dialogue from the handler since that would allow the site to continuously pop up confirm dialogues rather than navigating away from the page. 大多数浏览器不允许您从处理程序触发确认对话,因为这将允许站点不断弹出确认对话而不是导航离开页面。 Instead, you should return the message you want to display, for example: 相反,您应该返回要显示的消息,例如:

$(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
});

If you want to run additional javascript after the resultant dialogue has exited, add an onunload listener. 如果要在结果对话框退出后运行其他javascript,请添加onunload侦听器。

EDIT 编辑

As is pointed out in the comments, these events differ from browser to browser. 正如评论中指出的那样,这些事件因浏览器而异。 For example, the latest version of gecko (firefox) does not allow custom messages. 例如,最新版本的gecko(firefox)不允许自定义消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM