Detecting Browser History Actions

后端 未结 2 1857
时光说笑
时光说笑 2021-02-07 12:30

I am building a Html 5 website using push state and I wondering whether its possible in javascript or JQuery to detect whether the browser\'s back button has been pushed. I woul

相关标签:
2条回答
  • 2021-02-07 12:50

    And for AngularJS

    $window.onpopstate = function(e) {
        $window.alert("location: " + $location.path());
    }
    
    0 讨论(0)
  • 2021-02-07 13:04

    You're looking for the popstate event.

    An example:

    window.onpopstate = function(event) {
        alert("location: " + document.location);
    }
    

    Or with the ever-popular jQuery:

    $(window).on('popstate',function(event) {
        alert("location: " + document.location);
    });
    

    This fires whenever history is accessed, such as back/forward. A quick note, in Chrome this also fires on the page load, so a quick way around is to check if the event is null.

    if(event.originalEvent.state!=null){
        // do something
    }
    

    Another good resource is the History.js jQuery plugin, which has a fallback using hashtags and such. It also makes detection of popstate events very straightforward.

    0 讨论(0)
提交回复
热议问题