Yar*_*rin 5 javascript hash firefox url-parsing url-parameters
请考虑以下代码:
hashString = window.location.hash.substring(1);
alert('Hash String = '+hashString);
Run Code Online (Sandbox Code Playgroud)
使用以下哈希运行时:
#车=镇%20%26%20Country
Chrome和Safari的结果将是:
车=镇%20%26%20Country
但在Firefox(Mac和PC)中将是:
汽车=城镇和乡村
因为我使用相同的代码来解析查询和哈希参数:
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;
}
Run Code Online (Sandbox Code Playgroud)
Firefox的特质在这里打破了它:汽车座位结束了"城镇",没有国家.
有没有一种安全的方法来解析跨浏览器的哈希参数,或修复Firefox如何读取它们?
注意:此问题仅限于Firefox解析HASH参数.使用查询字符串运行相同的测试时:
queryString = window.location.search.substring(1);
alert('Query String = '+queryString);
Run Code Online (Sandbox Code Playgroud)
所有浏览器都会显示:
车=镇%20%26%20Country
解决方法是使用
window.location.toString().split('#')[1] // car=Town%20%26%20Country
Run Code Online (Sandbox Code Playgroud)
代替
window.location.hash.substring(1);
Run Code Online (Sandbox Code Playgroud)
我可以建议一个不同的方法(看起来更容易理解恕我直言)
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;
}
Run Code Online (Sandbox Code Playgroud)
测试用例
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"}
Run Code Online (Sandbox Code Playgroud)