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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-30 10:53:10927browse

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

Removing Hash from URL Without Page Refresh Using JavaScript

When working with URLs, it is often desirable to remove the hash fragment (#something) without causing the page to refresh. This can be achieved using the HTML5 History API, which allows for manipulation of the location bar.

One solution is:

window.location.hash = '';

However, this only removes the hash's content, leaving the # symbol in the URL.

For a more comprehensive solution:

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

This method works in Chrome, Firefox, Safari, Opera, and IE 10. For browsers that do not support it, a graceful degradation script can be used:

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

        loc.hash = "";

        // Restore scroll offset to avoid flickering
        document.body.scrollTop = scrollV;
        document.body.scrollLeft = scrollH;
    }
}

By utilizing this technique, you can effectively remove the hash from a URL without causing the page to refresh, regardless of browser support.

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

Statement:
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