Background: I have an HTML page which lets you expand certain content. As only small portions of the page need to be loaded for such an expansion, it's done via JavaScript, and not by directing to a new URL/ HTML page. However, as a bonus the user is able to permalink to such expanded sections, i.e. send someone else a URL like
http://example.com/#foobar
and have the "foobar" category be opened immediately for that other user. This works using parent.location.hash = 'foobar', so that part is fine.
Now the question: When the user closes such a category on the page, I want to empty the URL fragment again, i.e. turn http://example.com/#foobar into http://example.com/ to update the permalink display. However, doing so using parent.location.hash = ''
causes a reload of the whole page (in Firefox 3, for instance), which I'd like to avoid. Using window.location.href = '/#'
won't trigger a page reload, but leaves the somewhat unpretty-looking "#" sign in the URL. So is there a way in popular browsers to JavaScript-remove a URL anchor including the "#" sign without triggering a page refresh?
history. pushState({page: "another"}, "another page", "example. html"); This will change the URL, but not reload the page.
Method 2: Adding a new state with pushState() Method: The pushState() method is used to add a new history entry with the properties passed as parameters. This will change the current URL to the new state given without reloading the page.
To remove the hash URL, you can use the replaceState method on the history API to remove the hash location. Example: HTML.
In a URL, a hash mark, number sign, or pound sign ( # ) points a browser to a specific spot in a page or website. It is used to separate the URI of an object from a fragment identifier. When you use a URL with a # , it doesn't always go to the correct part of the page or website.
As others have mentioned, replaceState in HTML5 can be used to remove the URL fragment.
Here is an example:
// remove fragment as much as it can go without adding an entry in browser history: window.location.replace("#"); // slice off the remaining '#' in HTML5: if (typeof window.history.replaceState == 'function') { history.replaceState({}, '', window.location.href.slice(0, -1)); }
Since you are controlling the action on the hash value, why not just use a token that means "nothing", like "#_" or "#default".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With