How to Detect Browser Back Button event - Cross Browser

后端 未结 16 2735
鱼传尺愫
鱼传尺愫 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:41

    The document.mouseover does not work for IE and FireFox. However I have tried this :

    $(document).ready(function () {
      setInterval(function () {
        var $sample = $("body");
        if ($sample.is(":hover")) {
          window.innerDocClick = true;
        } else {
          window.innerDocClick = false;
        }
      });
    
    });
    
    window.onhashchange = function () {
      if (window.innerDocClick) {
        //Your own in-page mechanism triggered the hash change
      } else {
        //Browser back or forward button was pressed
      }
    };
    

    This works for Chrome and IE and not FireFox. Still working to get FireFox right. Any easy way on detecting Browser back/forward button click are welcome, not particularly in JQuery but also AngularJS or plain Javascript.

    0 讨论(0)
  • 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:

    <script>
    // jQuery
    $(window).on('popstate', function (e) {
        var state = e.originalEvent.state;
        if (state !== null) {
            //load content with ajax
        }
    });
    
    // Vanilla javascript
    window.addEventListener('popstate', function (e) {
        var state = e.state;
        if (state !== null) {
            //load content with ajax
        }
    });
    </script>
    

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

    0 讨论(0)
  • 2020-11-21 23:45
     <input style="display:none" id="__pageLoaded" value=""/>
    
    
     $(document).ready(function () {
            if ($("#__pageLoaded").val() != 1) {
    
                $("#__pageLoaded").val(1);
    
    
            } else {
                shared.isBackLoad = true;
                $("#__pageLoaded").val(1);  
    
                // Call any function that handles your back event
    
            }
        });
    

    The above code worked for me. On mobile browsers, when the user clicked on the back button, we wanted to restore the page state as per his previous visit.

    0 讨论(0)
  • 2020-11-21 23:47

    Correct answer is already there to answer the question. I want to mention new JavaScript API PerformanceNavigationTiming, it's replacing deprecated performance.navigation.

    Following code will log in console "back_forward" if user landed on your page using back or forward button. Take a look at compatibility table before using it in your project.

    var perfEntries = performance.getEntriesByType("navigation");
    for (var i = 0; i < perfEntries.length; i++) {
        console.log(perfEntries[i].type);
    }
    
    0 讨论(0)
  • 2020-11-21 23:48

    I tried the above options but none of them is working for me. Here is the solution

    if(window.event)
       {
            if(window.event.clientX < 40 && window.event.clientY < 0)
            {
                alert("Browser back button is clicked...");
            }
            else
            {
                alert("Browser refresh button is clicked...");
            }
        }
    

    Refer this link http://www.codeproject.com/Articles/696526/Solution-to-Browser-Back-Button-Click-Event-Handli for more details

    0 讨论(0)
  • 2020-11-21 23:49

    A full-fledged component can be implemented only if you redefine the API (change the methods of object ' history ') I will share the class just written. Tested on Chrome and Mozilla Support only HTML5 and ECMAScript5-6

    class HistoryNavigation {
        static init()
        {
            if(HistoryNavigation.is_init===true){
                return;
            }
            HistoryNavigation.is_init=true;
    
            let history_stack=[];
            let n=0;
            let  current_state={timestamp:Date.now()+n};
            n++;
            let init_HNState;
            if(history.state!==null){
                current_state=history.state.HNState;
                history_stack=history.state.HNState.history_stack;
                init_HNState=history.state.HNState;
            } else {
                init_HNState={timestamp:current_state.timestamp,history_stack};
            }
            let listenerPushState=function(params){
                params=Object.assign({state:null},params);
                params.state=params.state!==null?Object.assign({},params.state):{};
                let h_state={ timestamp:Date.now()+n};
                n++;
                let key = history_stack.indexOf(current_state.timestamp);
                key=key+1;
                history_stack.splice(key);
                history_stack.push(h_state.timestamp);
                h_state.history_stack=history_stack;
                params.state.HNState=h_state;
                current_state=h_state;
                return params;
            };
            let listenerReplaceState=function(params){
                params=Object.assign({state:null},params);
                params.state=params.state!==null?Object.assign({},params.state):null;
                let h_state=Object.assign({},current_state);
                h_state.history_stack=history_stack;
                params.state.HNState=h_state;
                return params;
            };
            let desc=Object.getOwnPropertyDescriptors(History.prototype);
            delete desc.constructor;
            Object.defineProperties(History.prototype,{
    
                replaceState:Object.assign({},desc.replaceState,{
                    value:function(state,title,url){
                        let params={state,title,url};
                        HistoryNavigation.dispatchEvent('history.state.replace',params);
                        params=Object.assign({state,title,url},params);
                        params=listenerReplaceState(params);
                        desc.replaceState.value.call(this,params.state,params.title,params.url);
                    }
                }),
                pushState:Object.assign({},desc.pushState,{
                    value:function(state,title,url){
                        let params={state,title,url};
                        HistoryNavigation.dispatchEvent('history.state.push',params);
                        params=Object.assign({state,title,url},params);
                        params=listenerPushState(params);
                        return desc.pushState.value.call(this, params.state, params.title, params.url);
                    }
                })
            });
            HistoryNavigation.addEventListener('popstate',function(event){
                let HNState;
                if(event.state==null){
                    HNState=init_HNState;
                } else {
                    HNState=event.state.HNState;
                }
                let key_prev=history_stack.indexOf(current_state.timestamp);
                let key_state=history_stack.indexOf(HNState.timestamp);
                let delta=key_state-key_prev;
                let params={delta,event,state:Object.assign({},event.state)};
                delete params.state.HNState;
                HNState.history_stack=history_stack;
                if(event.state!==null){
                    event.state.HNState=HNState;
                }
                current_state=HNState;
                HistoryNavigation.dispatchEvent('history.go',params);
            });
    
        }
        static addEventListener(...arg)
        {
            window.addEventListener(...arg);
        }
        static removeEventListener(...arg)
        {
            window.removeEventListener(...arg);
        }
        static dispatchEvent(event,params)
        {
            if(!(event instanceof Event)){
                event=new Event(event,{cancelable:true});
            }
            event.params=params;
            window.dispatchEvent(event);
        };
    }
    HistoryNavigation.init();
    
    // exemple
    
    HistoryNavigation.addEventListener('popstate',function(event){
        console.log('Will not start because they blocked the work');
    });
    HistoryNavigation.addEventListener('history.go',function(event){
        event.params.event.stopImmediatePropagation();// blocked popstate listeners
        console.log(event.params);
        // back or forward - see event.params.delta
    
    });
    HistoryNavigation.addEventListener('history.state.push',function(event){
        console.log(event);
    });
    HistoryNavigation.addEventListener('history.state.replace',function(event){
        console.log(event);
    });
    history.pushState({h:'hello'},'','');
    history.pushState({h:'hello2'},'','');
    history.pushState({h:'hello3'},'','');
    history.back();
    
        ```
    
    
    0 讨论(0)
提交回复
热议问题