How to call an event when browser back button is clicked

后端 未结 2 1728
长情又很酷
长情又很酷 2021-01-13 04:38

How to call a jquery event when browser back button is clicked. I am using a single page application in asp.net mvc and i want to show a confirm box to leave the screen when

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-13 04:47

    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) {
                    // alert('Browser Back or Forward button was pressed.');
                     }
        if(window.onBrowserHistoryButtonClicked ){
        window.onBrowserHistoryButtonClicked ();
                }
            });
        }
    });
    

提交回复
热议问题