Window.location.hash Problema en Firefox
-
27-10-2019 - |
Pregunta
Considere el siguiente código:
hashString = window.location.hash.substring(1);
alert('Hash String = '+hashString);
Cuando se ejecuta con el siguiente hash:
#coche = ciudad%20%26%20Country
el resultado en Cromo y Safari estarán:
coche = ciudad%20%26%20Country
pero en Firefox (Mac y PC) será:
coche = ciudad y país
Porque uso el mismo código para analizar la consulta y los parámetros hash:
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;
}
La idiosincrasia de Firefox aquí lo rompe aquí: el par de parámetros termina siendo "pueblo", ningún país.
¿Existe una forma segura de analizar los parámetros de hash en los navegadores o para arreglar cómo Firefox los lee?
NOTA: Este problema se limita al análisis de Firefox de los parámetros hash. Al ejecutar la misma prueba con cadenas de consulta:
queryString = window.location.search.substring(1);
alert('Query String = '+queryString);
Todos los navegadores mostrarán:
coche = ciudad%20%26%20Country
Solución
Una solución es usar
window.location.toString().split('#')[1] // car=Town%20%26%20Country
En vez de
window.location.hash.substring(1);
¿Puedo sugerir también un método diferente (parece más simple de entender en mi humilde opinión)
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;
}
Caso de prueba
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"}
Otros consejos
window.location.toString().split('#')[1]
funcionará en la mayoría de los casos, pero no si el hash contiene otro hash (codificado o de otro tipo).
En otras palabras split('#')
podría devolver una matriz de longitud> 2. Pruebe lo siguiente (o variación propia) en su lugar:
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
}