Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove fragment in URL with JavaScript w/out causing page reload

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?

like image 980
Philipp Lenssen Avatar asked Nov 06 '08 15:11

Philipp Lenssen


People also ask

How do I use Javascript to modify the URL without reloading the page?

history. pushState({page: "another"}, "another page", "example. html"); This will change the URL, but not reload the page.

How do I change URL without reloading?

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.

How do you remove hash?

To remove the hash URL, you can use the replaceState method on the history API to remove the hash location. Example: HTML.

What does hash in URL mean?

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.


2 Answers

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)); } 
like image 117
Matmas Avatar answered Sep 18 '22 09:09

Matmas


Since you are controlling the action on the hash value, why not just use a token that means "nothing", like "#_" or "#default".

like image 29
Diodeus - James MacFarlane Avatar answered Sep 20 '22 09:09

Diodeus - James MacFarlane