How to make the browser back button disregard hash tags?

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

    That's intentional browser behavior, and is the proper use of hash tags. As a result, I suggest considering whether the javascript that is using those hash tags is the problem, and to change it to a different storage method. Effectively, you can just use a globally available javascript variable for that purpose, because no page reload will be happening so the variable will persist.

    window.stage = 'start';
    
    // Another stage
    window.stage = 'onfire'
    

    You'll still want to suppress the standard behavior from clicks for js elements, of course.

    Alternatively, if you want the stages to be stored, but not "navigatable", you can consider using localstorage on more modern browsers.

    EDIT: (based on the new information)

    The thing that you are trying to do is an extremely common scenario in webdev because pages don't save much by way of their user's state/information.

    You want to store information about what your users have completed, what stage they are at in a process. Even when they have navigated away from a page.

    There are somewhat limited number of places to "store" data: the hash, localStorage, cookies, or client-side, and that's about it. If I were a user of your page, I suspect that I would want my data stored regardless -how- I navigate through your app.

    So I suggest considering a better location for storing the state of your webpage than the hash, which is generally designed for navigation. If they're going to be logged in via php, just store it via php to the database. If not, then store it to localStorage where available and fallback to cookies, or just use cookies.

    Your end navigation may look as tangled as this: start page > processing page > any other page > processing page > leave the site > return to processing page

    But each time they return to the processing page, their data will be there stored, in the state that they left it.

    If you must use a hash for some reason, @Sidnicious's answer has a way that may skip the step of creating a history entry, so if you use that for all the stages except the one before you change pages, your history will look like this: start>processing.php>processing.php#final>otherpage.php which may cut down the back button hits down to an acceptable level.

提交回复
热议问题