How to make the browser back button disregard hash tags?

后端 未结 5 2252
温柔的废话
温柔的废话 2021-02-14 07:57

I have a website that uses hashes to open/close some tabs and layers on the current page. The reason behind using hashes is, that if a user visits another page via a link and th

5条回答
  •  梦谈多话
    2021-02-14 08:39

    I've encountered with the same issue as the one you described. I agree with Ivan Ivković's idea. The following is my code and it works for my case. I'm new to JS, but hope it helps.

    var counter = 0;
    window.onhashchange = function() {
        window.history.replaceState({visited: ++counter}, "visited page", 
    
    window.location.search+window.location.hash);
    }
    
    window.onpopstate = function(event) {
        if(event.state.visited && counter>event.state.visited) {
        counter -= 2;
        window.history.go(-1*event.state.visited);
        }
        else {
        counter = event.state.visited;
        }
    }
    

提交回复
热议问题