English 中文(简体)
Encoding of window.location.hash
原标题:

Does window.location.hash contain the encoded or decoded representation of the url part?

When I open the same url (http://localhost/something/#%C3%BC where %C3%BCtranslates to ü) in Firefox 3.5 and Internet Explorer 8, I get different values for document.location.hash:

  • IE8: #%C3%BC
  • FF3.5:

Is there a way to get one variant in both browsers?

最佳回答

Unfortunately, this is a bug in Firefox as it decodes location.hash an extra time when it is accessed. For example, try this in Firefox:

location.hash = "#%30";
location.hash === "#0"; // This is wrong, it should be "#%30"

The only cross-browser solution is to just use (location.href.split("#")[1] || "") instead for getting the hash. Setting the hash using location.hash seems to work correctly for all browsers that support location.hash though.

问题回答

Answering to my own question, my current solution is to parse window.location.href instead of using window.location.hash, because the former is always (i.e. in every browser) url-encoded. Therefore the decodeURIComponent function CMS proposed can always be used safely. YUI does the same, therefore it can t be that wrong...

You can use decodeURIComponent, it will return in all cases:

decodeURIComponent( #%C3%BC ); // #ü
decodeURIComponent( #ü ); // #ü

Try it out here.

Actually in my version of Firefox (3.5 on Linux), if I type "#%C3%BC" as a hash in the URL, the URL itself actually transforms to unicode with "#ü". But you have appeared to answered your own question -- in Firefox, the browser transforms entity escape codes in the URL, while in IE, it does not.

My advice is actually this: Instead of putting "#%C3%BC" in the URL at all, just use full unicode in your hashes and URLs. Is that an option? It should work fine in any modern browser.





相关问题
CSS working only in Firefox

I am trying to create a search text-field like on the Apple website. The HTML looks like this: <div class="frm-search"> <div> <input class="btn" type="image" src="http://www....

image changed but appears the same in browser

I m writing a php script to crop an image. The script overwrites the old image with the new one, but when I reload the page (which is supposed to pickup the new image) I still see the old one. ...

Firefox background image horizontal centering oddity

I am building some basic HTML code for a CMS. One of the page-related options in the CMS is "background image" and "stretch page width / height to background image width / height." so that with large ...

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签