浏览器返回按钮上的确认框

Confirm box on browser back button

本文关键字:确认 返回 按钮 浏览器      更新时间:2023-09-26

我想在浏览器的背面或刷新按钮上捕捉事件。我并没有找到任何一个完美的解决方案,只捕获back事件,并且兼容所有浏览器。请提供一些解决方案。

提前谢谢。

您可以使用HTML5历史API中的事件处理程序onpopstate,如下所示:

$(document).ready(function() {
if (window.history && window.history.pushState) {
$(window).on('popstate', function() {
  //confirmation box
  confirm('Back button clicked!');
});
 }
});

请注意,您需要有一个页面返回…

window.userInteractionTimeout = null;
window.userInteractionInHTMLArea = false;
window.onBrowserHistoryButtonClicked = null; // This will be your event handler for browser navigation buttons clicked
$(document).ready(function() {
    $(document).mousedown(function() {
        clearTimeout(window.userInteractionTimeout);
        window.userInteractionInHTMLArea = true;
        window.userInteractionTimeout = setTimeout(function() {
            window.userInteractionInHTMLArea = false;
        }, 500);
    });
    $(document).keydown(function() {
        clearTimeout(window.userInteractionTimeout);
        window.userInteractionInHTMLArea = true;
        window.userInteractionTimeout = setTimeout(function() {
            window.userInteractionInHTMLArea = false;
        }, 500);
    });
    if (window.history && window.history.pushState) {
        $(window).on('popstate', function() {
            if (!window.userInteractionInHTMLArea) {
                //document.location.href = "logOff.htm";
                setTimeout(function(){  var answer = confirm("Are you Sure?? This will expire your session");
                if(answer == true)
                    {
                    document.location.href = "logOff.htm";  
                    }
                },100 );

                //alert('Browser Back or Forward button was pressed.');
            }
            if (window.onBrowserHistoryButtonClicked) {
                window.onBrowserHistoryButtonClicked();
            }
        });
    }
});