简体   繁体   English

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

[英]Confirm box on browser back button

I want to catch the event on back or refresh button of browser. 我想在浏览器的返回或刷新按钮上捕获事件。 I didn't found any perfect solution that catches only back event and which is compatible with all browsers. 我没有找到任何完美的解决方案,它只能捕获事件并与所有浏览器兼容。 please provide some solution. 请提供一些解决方案。

Thanks in advance. 提前致谢。

You can use the event handler onpopstate from HTML5 history API, like this : 您可以从HTML5历史API使用事件处理程序onpopstate ,如下所示:

$(document).ready(function() {

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

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

Note that you need to have a page to go back to... 请注意,您需要有一个页面才能返回到...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM