Potential problems setting window.location.hash

I have some javascript code which, at one point, sets window.location.hash to a specific string. This works fine in Firefox 3, but I want to know if I will run into problems with this later, i.e. is this a cross-browser solution (IE6 included)?

Also, I am using ReallySimpleHistory. Will this mess up its internal state?


window.location.hash has been around since JavaScript was introduced in Netscape Navigator 2 back in 1995. It was first supported by Microsoft in Internet Explorer 3 in 1996. I think you can be reasonably certain that every JS-capable browser supports it.

From a quick glance through the source, it looks as if ReallySimpleHistory makes pretty extensive use of this property, so you may well break it. You might want to use its add(newLocation) method instead (which works by setting window.location.hash).


 var hash = location.hash.slice(1);


 location.hash="#" + 'string';

Old thread i know, but window.location.hash is subject to a size limit as well. If you’re passing large amounts of data, and want to save state in the hash, you could run into some issues.

IE will give you the error:
SCRIPT5 - Access denied. if you try to assign a hash that is over the limit
which is super useful.

Just food for thought.

All “modern” (a.k.a A-Graded) browsers allow to set hash and do not reload the page when doing so. The ones that do reload the page are some of the older ones, such as Safari 2.0.4 and Opera 8.5x.

Read More:   Define a global variable in a JavaScript function

See my Usenet post on comp.lang.javascript where I explain it in a bit more detail.

Also note, that HTML5 finally specifies that hash setter should change actual hash but not reload the page.

Setting window.location.hash works fine in IE6 & IE7.

In some occasions, reading window.location.hash under IE6 right after a set will return the old value, but the browser has set the hash successfully. An example:


/* Sometimes, it will return the old value,
   I haven't figured out why it does that, and
   it's rather rare. */

If you are just using it to set it, you shouldn’t run into any problems.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts