2

我到处搜索,但找不到我正在寻找的确切解决方案。我需要一个javascript代码,当用户尝试退出页面时,会弹出一个带有“留在页面”或“离开页面”选项的警报框。如果用户留下来,它会将他们重定向到另一个页面,如果他们选择离开,它就会离开。类似于退出飞溅的东西。我知道这是不好的做法,但这是客户想要的。任何帮助将不胜感激。在此先感谢您的帮助。

4

2 回答 2

3

这很hacky,但可以完成工作

var triedToLeave = false;
function onBeforeUnload(){
    triedToLeave = true;
    return "you can put your own message here";
}
setInterval( function (){
     if( triedToLeave ){
         window.removeEventListener( "beforeunload", onBeforeUnload, false );
         document.location.href = "http://stackoverflow.com/";
     }
}, 2000 );
window.addEventListener( "beforeunload", onBeforeUnload, false);

编辑固定功能

于 2013-11-14T21:55:10.530 回答
1

这应该会实现您想要的最终结果,尽管它在技术上将用户引导到启动页面,然后再做出决定。

var notScriptLeaving = true;
window.onbeforeunload = function() {
    if (notScriptLeaving) {
        notScriptLeaving = false;
        window.location = 'http://www.example.com/'; //Splash page url goes here
        return "Are you sure you want to navigate away?";
    }
}
于 2013-11-14T22:17:46.680 回答