简体   繁体   中英

How to go back to the previous page when browser back button is clicked in a webpage even when the hash is changed?

I have a web page in which my anchor tags refer to one of the elements within the same page using #id. But this changes my URL as it adds the #id into the suffix. So now when I want to go back to the page from where I came by clicking the back button of the browser, it doesn't go back to the previous page instead it goes back to the hash selections I have made by clicking the anchor tags. Please help me by giving a solution to this.

When you use a hash route it creates a new record in the browser history the same as if you navigated to a new page. So if you navigate on your site from a page to a hash route on that page, then navigate to a new page, you will have to click on the back button twice to get back to your original location.

So if you navigate https://example.com -> https://example.com#myHash -> https:/example.com/another-page then the first back button click will navigate to https://example.com#myHash and the second back button click will navigate to https://example.com

Hope that helps

You can use history.replaceState() function from History API to achieve such behavior. When user will click on anchor you will just replace current history item instead of adding a new one.

Edit: window.location.replace()

Another approach is to use window.location.replace() which is does not adds a new entry to browser's History:

The Location.replace() method replaces the current resource with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session History, meaning the user won't be able to use the back button to navigate to it.

So what can be done to achieve the desired result is to add an onclick handler on the body element with a logic inside which will replace current location if current location is not a homepage (or any other page). This handler will look similar to the code below:

function handler (event) {
    if (!isAnchor(event.target) return;                     // return if clicked element is not an anchor (isAnchor function should be also implemented by you. For example, you can add some class on every anchor and check if clicked element is <a> tag with this class)
    if (window.location.href !== window.location.origin) {  // check if you are currently on the homepage
        event.preventDefault();                             // if not on homepage then prevent default <a> tag redirect 
        window.location.replace(event.target.href);         // and replace current history item URL with the new URL
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM