Domanda

Considera il seguente codice:

hashString = window.location.hash.substring(1);
alert('Hash String = '+hashString);

Quando esegui il seguente hash:

#auto = città%20%26%20country

il risultato in Cromo e Safari sarà:

Auto = città%20%26%20Pountry

ma in Firefox (Mac e PC) saranno:

auto = città e paese

Perché utilizzo lo stesso codice per analizzare la query e hash Params:

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;

    }

Idiosincrasia di Firefox qui lo rompe: il parametro dell'auto finisce per essere "città", nessun paese.

Esiste un modo sicuro per analizzare i parametri di hash tra i browser o per risolvere il modo in cui Firefox li legge?


NOTA: Questo problema è limitato all'analisi dei parametri di Hash da parte di Firefox. Quando si esegue lo stesso test con le corde di query:

queryString = window.location.search.substring(1);
alert('Query String = '+queryString);

Tutti i browser mostreranno:

Auto = città%20%26%20Pountry

È stato utile?

Soluzione

Una soluzione alternativa è da usare

window.location.toString().split('#')[1] // car=Town%20%26%20Country

Invece di

window.location.hash.substring(1);

Posso anche suggerire un metodo diverso (sembra più semplice per capire 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;
}

Caso di prova

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"}

Altri suggerimenti

window.location.toString().split('#')[1] funzionerà nella maggior parte dei casi ma non se l'hash contiene un altro hash (codificato o altro).

In altre parole split('#') potrebbe restituire un array di lunghezza> 2. Prova invece quanto segue (o propria variazione):

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
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top