window.location.hash issue in firefox
-
27-10-2019 - |
質問
次のコードを検討してください。
hashString = window.location.hash.substring(1);
alert('Hash String = '+hashString);
次のハッシュで実行するとき:
#car = town%20%26%20country
の結果 クロム と サファリ します:
car = town%20%26%20country
しかし、 Firefox (MacとPC)は次のとおりです。
Car = Town&Country
同じコードを使用してクエリとハッシュパラマを解析するためです。
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;
}
ここでのFirefoxの特異性はそれを壊します:車のパラマは「町」であり、国はありません。
ブラウザ全体でハッシュパラマを解析する安全な方法はありますか、それともFirefoxの読み方を修正しますか?
ノート: この問題は、FirefoxのHash Paramsの解析に限定されています。クエリ文字列で同じテストを実行するとき:
queryString = window.location.search.substring(1);
alert('Query String = '+queryString);
すべてのブラウザが表示されます:
car = town%20%26%20country
解決
回避策は使用することです
window.location.toString().split('#')[1] // car=Town%20%26%20Country
それ以外の
window.location.hash.substring(1);
別の方法も提案してもいいですか(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;
}
テストケース
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"}
他のヒント
window.location.toString().split('#')[1]
ほとんどの場合は機能しますが、ハッシュに別のハッシュ(エンコードまたはその他)が含まれている場合は機能しません。
言い換えると split('#')
長さ2> 2の配列を返す可能性があります。代わりに、次の(または独自のバリエーション)を試してください。
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
}