Home > Web Front-end > JS Tutorial > How to Remove a URL Hash Without Refreshing the Page Using JavaScript?

How to Remove a URL Hash Without Refreshing the Page Using JavaScript?

Patricia Arquette
Release: 2024-11-29 15:00:13
Original
505 people have browsed it

How to Remove a URL Hash Without Refreshing the Page Using JavaScript?

Removing the Hash from URL without Page Refresh Using JavaScript

When you encounter URLs like "http://example.com#something" with a hash component (#) at the end, removing it without refreshing the page can prove challenging. Traditional methods involving setting the "window.location.hash" to an empty string fail to remove the hash symbol itself.

Solution: HTML5 History API

Modern browsers provide a solution through the HTML5 History API. By utilizing the "history.pushState()" function, we can modify the location bar to display a new URL without triggering a page refresh.

function removeHash() {
    history.pushState("", document.title, window.location.pathname
                                                       + window.location.search);
}
Copy after login

This method effectively removes the hash from the URL in current and compatible browsers, including Chrome, Firefox, Safari, Opera, and Internet Explorer 10 and above.

Graceful Degradation for Unsupported Browsers

For browsers that do not support the History API, you can employ a graceful degradation script:

function removeHash() {
    var scrollV, scrollH, loc = window.location;
    if ("pushState" in history)
        history.pushState("", document.title, loc.pathname + loc.search);
    else {
        // Preserve current scroll position
        scrollV = document.body.scrollTop;
        scrollH = document.body.scrollLeft;

        loc.hash = "";

        // Restore scroll position
        document.body.scrollTop = scrollV;
        document.body.scrollLeft = scrollH;
    }
}
Copy after login

This approach ensures compatibility across different browsers, eliminating the hash symbol without causing page refreshes.

Note:

  • To replace the current history entry instead of adding a new one, use "replaceState()" instead of "pushState()".
  • Removing the hash is dependent on browser support. However, this solution provides a comprehensive approach that covers both supported and unsupported browsers.

The above is the detailed content of How to Remove a URL Hash Without Refreshing the Page Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template