How to make the browser back button disregard hash tags?

后端 未结 5 2246
温柔的废话
温柔的废话 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:49

    As far as I know, you can’t solve this without JavaScript. The fragment is part of the URL, and when it changes, the new URL is added to history.

    I would suggest using location.replace() when you want to change the URL without creating a history entry. Instead of setting window.location.hash, try this:

    window.location.replace('#1');
    

    I’ll leave it up to you to pick the best way to integrate this into your website, but here’s one minimally-tested option for catching clicks on links:

    $(window).on('click', 'a', function(e){
        var href = $(e.target).attr('href');
        if (href && href[0] === '#') {
            window.location.replace(e.target.href);
            return false;
        }
    });
    

提交回复
热议问题