JustinMarsan

Force refresh of a page when the hash changes

By default, when clicking on a link that references to the same page, but with a different hash, Firefox (and eventually other browsers) won't do anything... Here's a fix.

The issue might be a little obscure so I'll explain a little better, with an example.

Let's assume that you are working on a page that you access throught http://example.com/my-page.

One of the features of this page is to do something based on the has of this url, so for instance you would get http://example.com/my-page#category=script and with that you would... do whatever you need to.

So far, it's working fine, but now, what if you want to have a link that would link to http://example.com/my-page#category=book-reviews instead ? Nothing !. The reason for that is that the browser will try to scroll to the element in the page with such id, basic anchor tag linking. And doing so, it won't refresh the page, and that's what we're going to fix now.

Getting the hash

If your code is generating the has, you shouldn't have much problem getting the hash (everything after the #) on it's own, if you don't, here is a great technique to get just the hash (or any other part of a url) from it's complete string.

Changing the hash in the current url

No magic here, we're just changing the value of the hash in the current url we're browsing :

var hash = "category=book-reviews";
window.location.hash = hash;

Forcing the refresh

If we stop here, still nothing happened, unless you look at your url. So let's just make the page refresh :

window.location.reload();

This is overall rather simple but the issue can be difficult to figure out, and the solution isn't as obvious as it seems, I figured I'd share the way to solve it.