question window.location.hash dans Firefox
-
27-10-2019 - |
Question
Considérez le code suivant:
hashString = window.location.hash.substring(1);
alert('Hash String = '+hashString);
Lors de l'exécution avec le hachage suivant:
# voiture = ville% 20% 26% 20Country
le résultat Chrome et Safari sera:
voiture = ville% 20% 26% 20Country
Firefox (Mac et PC) sont les suivants:
voiture = Town & Country
Parce que j'utilise le même code pour analyser la requête et params hachage:
function parseParams(paramString) {
var params = {};
var e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&;=]+)=?([^&;]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = paramString;
while (e = r.exec(q))
params[d(e[1])] = d(e[2]);
return params;
}
idiosyncrasie de Firefox brise voilà. La voiture serpente jusqu'à être param « Ville », aucun pays
Yat-il un moyen sûr de params parse de hachage dans les navigateurs, ou de fixer la façon dont Firefox les relit?
NOTE: Cette question se limite à l'analyse de Firefox de params HASH. Lorsque vous exécutez le même test avec les chaînes de requête:
queryString = window.location.search.substring(1);
alert('Query String = '+queryString);
tous les navigateurs montreront:
voiture = ville% 20% 26% 20Country
La solution
A workaround is to use
window.location.toString().split('#')[1] // car=Town%20%26%20Country
Instead of
window.location.hash.substring(1);
May I also suggest a different method (looks simpler to understand IMHO)
function getHashParams() {
// Also remove the query string
var hash = window.location.toString().split(/[#?]/)[1];
var parts = hash.split(/[=&]/);
var hashObject = {};
for (var i = 0; i < parts.length; i+=2) {
hashObject[decodeURIComponent(parts[i])] = decodeURIComponent(parts[i+1]);
}
return hashObject;
}
Test Case
url = http://stackoverflow.com/questions/7338373/window-location-hash-issue-in-firefox#car%20type=Town%20%26%20Country&car color=red?qs1=two&qs2=anything
getHashParams() // returns {"car type": "Town & Country", "car color": "red"}
Autres conseils
window.location.toString().split('#')[1]
will work in most cases but not if the hash contains another hash (encoded or otherwise).
In other words split('#')
might return an array of length>2. Try the following (or own variation) instead:
var url = location.href; // the href is unaffected by the Firefox bug
var idx = url.indexOf('#'); // get the first indexOf '#'
if (idx >= 0) { // '#' character is found
hash = url.substring(idx, url.length); //the window.hash is the remainder
} else {
return; // no hash is found... do something sensible
}