views:

451

answers:

2

Setting window.location.hash to null in Safari 3+ causes it to be set to #, e.g.

window.location.hash = '#foo' => #foo

But,

window.location.hash = null => #

Same occurs if you set it to an empty string instead of null. Behavior definitely occurs in Safari 3 + 4, and does not occur in FF 3 or 4.

Any workarounds for this? Granted, it is more of an aesthetically-motivated thing, but I'd still like consistent behavior across all browsers.

A: 

In Safari 4 (don't know about 3) this will make the # disappear, and the page will not reload.

window.location.hash = 'foo';
window.history.go(-1);

However, it will obviously mess with the browser history. If they click forward it will take them to http://whatever.com/#foo.

David
This is quite an incomplete solution. It does not work if the original URL had a hash in it and you wanted to remove it.
Andrew Hedges
That's because there is no complete solution as far as I know, feel free to enlighten us otherwise. This is obviously just a hack and not meant to be super robust.
David
A: 

Set hash to an empty string, not null. Null is not a valid value for the hash property (which is always a string). Works for me in Safari 3.2.1/Win. (Though not, for some reason in Opera 10... but then who cares? Is having a blank hash part on the end of the URL such a bad thing?)

bobince
setting location.hash = ''; will still leave the # sign in the url, which is what he's trying to avoid.
David