Search code examples
javascriptjqueryback-button

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.


Solution

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