简体   繁体   English

如果用户点击停留在页面上,则重定向的Javascript警报

[英]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.

相关问题 在用户单击“确定”之前,甜蜜警报将重定向 - Sweet alert redirects before the user clicks OK Javascript Alert并停留在当前页面上 - Javascript Alert and stay on the current page 如何在JavaScript中发出警报后留在同一页面上 - how to stay on same page after alert in JavaScript JavaScript警报框(保持在同一页面上)? - Javascript Alert Box (Stay on same page)? 当用户单击页面1上的按钮时,它将数据发送到页面2并重定向到页面3 - When a user clicks a button on page 1 it sends data to page 2 and redirects to page 3 我如何有条件地显示一个Javascript alert()来阻止页面提交,直到用户单击“确定”为止? - How do I conditionally display a Javascript alert() that blocks the page from submitting until the user clicks “OK”? 当用户在Django中单击“确定”后,如何触发Javascript警报,然后重定向页面? - How to fire a Javascript alert and then redirect the page after user clicks 'ok' in Django? 当用户单击甜蜜警报的确定按钮时,重定向到 web 页面 - Redirect to a web page when a user clicks on the ok button of the sweet alert 当用户单击“提交”按钮时如何防止退出时发出JavaScript警报 - How to prevent javascript alert on exit when user clicks on submit button 用户单击JavaScript警报上的“确定”按钮时更新表 - Updating table when user clicks OK button on a JavaScript alert
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM