How to Detect Browser Back Button event - Cross Browser

后端 未结 16 3197
鱼传尺愫
鱼传尺愫 2020-11-21 23:09

How do you definitively detect whether or not the user has pressed the back button in the browser?

How do you enforce the use of an in-page back button inside a sin

16条回答
  •  生来不讨喜
    2020-11-21 23:45

    You can try popstate event handler, e.g:

    window.addEventListener('popstate', function(event) {
        // The popstate event is fired each time when the current history entry changes.
    
        var r = confirm("You pressed a Back button! Are you sure?!");
    
        if (r == true) {
            // Call Back button programmatically as per user confirmation.
            history.back();
            // Uncomment below line to redirect to the previous page instead.
            // window.location = document.referrer // Note: IE11 is not supporting this.
        } else {
            // Stay on the current page.
            history.pushState(null, null, window.location.pathname);
        }
    
        history.pushState(null, null, window.location.pathname);
    
    }, false);
    

    Note: For the best results, you should load this code only on specific pages where you want to implement the logic to avoid any other unexpected issues.

    The popstate event is fired each time when the current history entry changes (user navigates to a new state). That happens when user clicks on browser's Back/Forward buttons or when history.back(), history.forward(), history.go() methods are programatically called.

    The event.state is property of the event is equal to the history state object.

    For jQuery syntax, wrap it around (to add even listener after document is ready):

    (function($) {
      // Above code here.
    })(jQuery);
    

    See also: window.onpopstate on page load


    See also the examples on Single-Page Apps and HTML5 pushState page:

    
    

    This should be compatible with Chrome 5+, Firefox 4+, IE 10+, Safari 6+, Opera 11.5+ and similar.

提交回复
热议问题