[英]Javascript alert that redirects if user clicks stay on page
I have searched everywhere and I cannot find the exact solution that I am looking for. 我到处搜索了,找不到确切的解决方案。 I need a javascript code that when the user tries to exit the page, an alert box pops up with the "stay on page" or "leave page" options.
我需要一个JavaScript代码,当用户尝试退出页面时,会弹出一个警告框,其中显示“停留在页面上”或“离开页面”选项。 If the user stays, it redirects them to another page and if they choose leave it leaves.
如果用户留下,它将重定向到另一个页面,如果他们选择离开,则离开。 Something similar to exit splash.
类似于出口飞溅。 I know this is poor practice but it is what the clients wants.
我知道这是不好的做法,但这是客户想要的。 Any help will be greatly appreciated.
任何帮助将不胜感激。 Thanks in advance for your help.
在此先感谢您的帮助。
This is hacky but will do the job 这很棘手,但可以胜任
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);
EDIT fixed function 编辑固定功能
This should accomplish the final result you want, though it technically directs the user to the splash page before they make their decision. 尽管可以从技术上指导用户在他们做出决定之前将其引导到初始页面,但这应该可以实现所需的最终结果。
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?";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.