浏览器后退按钮上的确认框

时间:2016-05-03 09:46:09

标签: javascript jquery back-button

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

提前致谢。

2 个答案:

答案 0 :(得分:0)

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

$(document).ready(function() {

if (window.history && window.history.pushState) {

$(window).on('popstate', function() {
  //confirmation box
  confirm('Back button clicked!');
});
 }
});

请注意,您需要有一个页面才能返回...

答案 1 :(得分:0)

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