Search code examples
javascriptjqueryfirefoxhashchange

Correctly encoded string gets decoded when pushed into window.location.hash


The goal: Correctly put a string from a data attribute into the window.location.hash.

The code:

map = {path: $(this).attr('data-path'), rev: $(this).attr('data-rev')};
window.location.hash = getMapParams(map);

function getMapParams(map) {
  s="";
  for(key in map) {
    value=eval("map."+key);
    if (s.length > 0) {
      s+="&";
    }
    s+=encodeURIComponent(key)+"="+encodeURIComponent(value);
  }
  return s;
}

The problem: As soon as the data-path attribute contains a space Firefox fails to put the hash correctly. The space will appear unencoded whereas in other browsers it's correctly encoded as %20.

The weird quirks: If I debug the code the string is listed with the encoded space.

The research done: I have found plenty solutions for correctly reading the hash in firefox. In one way or another this is working fine with my code.

The question: How do I stop Firefox from urldecoding the space(s) in a string I put in window.location.hash


Solution

  • I usually try to avoid window.location.hash because of it's not uniform across browsers.

    Thus rather than doing following

    window.location.hash = "some hash value";
    

    I would do

    window.location.href = window.location.href.split("#")[0] + "#" + encodeURIComponent("some hash value");
    

    Furthermore, although Firefox shows decoded hash in address bar (i.e. ' ' instead of %20), if you try to copy the address it is actually encoded. Thus what is getting shown is not what is in the URI.

    As an aside, I always access hash using following code

    var hash_val = window.location.href.split("#")[1] || "";