Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 201
Michael Avatar asked Nov 09 '09 20:11

Michael


People also ask

What is hash in window location?

The hash property of the Location interface returns a string containing a '#' followed by the fragment identifier of the URL — the ID on the page that the URL is trying to target. The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string, "" .

What is hash in HTML?

The hash property sets or returns the anchor part of the href attribute value. The href attribute specifies the destination of a link in an area. The anchor part is the part of the URL after the hash sign (#). Note: When this property is used to set the anchor part, do not include the hash sign (#).

What is decodeURIComponent?

The decodeURIComponent() function decodes a Uniform Resource Identifier (URI) component previously created by encodeURIComponent or by a similar routine.

How do I add a hash to a URL?

The hash of a url can be found by creating a new URL Javascript object from the URL string, and then using its hash property to get the value of the hash fragment. Note that this will include the # character also. If the url does not contains a hash, then an empty string "" will be returned.


1 Answers

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.

like image 189
Eli Grey Avatar answered Sep 21 '22 15:09

Eli Grey