Effortless Removal of URLs' Hash with JavaScript
Q: I have a URL like http://example.com#something, and I want to remove #something without refreshing the page. Using "window.location.hash = ''" didn't work.
A: The HTML5 History API provides an elegant solution. Here's a JavaScript function that does the trick:
function removeHash () { history.pushState("", document.title, window.location.pathname + window.location.search); }
This works in major browsers like Chrome, Firefox, Safari, Opera, and even IE 10.
For browsers that don't support the History API:
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 the current scroll offset scrollV = document.body.scrollTop; scrollH = document.body.scrollLeft; loc.hash = ""; // Restore the scroll offset to prevent flickering document.body.scrollTop = scrollV; document.body.scrollLeft = scrollH; } }
This solution may not be universally compatible, but it provides graceful degradation for browsers that don't support the History API.
The above is the detailed content of How to Effortlessly Remove a URL\'s Hash in JavaScript Without Reloading?. For more information, please follow other related articles on the PHP Chinese website!