简体   繁体   中英

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

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 (ie ' ' 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] || "";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM