Firefox 中的 window.location.hash 问题
考虑以下代码:
hashString = window.location.hash.substring(1);
alert('Hash String = '+hashString);
当使用以下哈希运行时:
#car=城镇%20%26%20国家
在 Chrome 和 Safari 中的结果将是:
汽车=城镇%20%26%20国家
但在 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;
}
Firefox 的特性在这里打破了它:汽车参数最终是“城镇”,没有国家。
有没有一种安全的方法来跨浏览器解析哈希参数,或者修复 Firefox 读取它们的方式?
注意:此问题仅限于 Firefox 对 HASH 参数的解析。当使用查询字符串运行相同的测试时:
queryString = window.location.search.substring(1);
alert('Query String = '+queryString);
所有浏览器都会显示:
汽车=城镇%20%26%20国家
Consider the following code:
hashString = window.location.hash.substring(1);
alert('Hash String = '+hashString);
When run with the following hash:
#car=Town%20%26%20Country
the result in Chrome and Safari will be:
car=Town%20%26%20Country
but in Firefox (Mac AND PC) will be:
car=Town & Country
Because I use the same code to parse query and 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;
}
Firefox's idiosyncrasy here breaks it: The car param winds up being "Town", no country.
Is there a safe way to parse hash params across browsers, or to fix how Firefox reads them?
NOTE: This issue is limited to Firefox's parsing of HASH params. When running the same test with query strings:
queryString = window.location.search.substring(1);
alert('Query String = '+queryString);
all browsers will show:
car=Town%20%26%20Country
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
解决方法是使用
而不是
May 我还建议使用不同的方法(看起来更容易理解恕我直言)
测试用例
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
A workaround is to use
Instead of
May I also suggest a different method (looks simpler to understand IMHO)
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
window.location.toString().split('#')[1]
在大多数情况下都有效,但如果哈希包含另一个哈希(编码或其他方式),则无效。换句话说,
split('#')
可能会返回一个长度>2 的数组。请尝试以下(或自己的变体):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: