javascript - Firefox 中的 window.location.hash 问题

标签 javascript firefox hash url-parameters url-parsing

考虑以下代码:

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

当使用以下哈希运行时:

#car=Town%20%26%20Country

ChromeSafari 中的结果将是:

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 参数的解析。使用查询字符串运行相同的测试时:

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);

我还可以建议一个不同的方法吗(恕我直言,看起来更容易理解)

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 =任何东西

getHashParams() // returns {"car type": "Town & Country", "car color": "red"}

关于javascript - Firefox 中的 window.location.hash 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7338373/

相关文章:

javascript - 本地主机\外部站点的 IE\Firefox 垃圾回收

c++ - 为嵌套自定义类型定义散列函数

javascript - 是否可以使用 C# 添加 Object 的属性

javascript - Highcharts : using same div to load a chart multiple times with different series data

javascript - 如何循环请求 promise API 请求调用?

arrays - 创建包含哈希的数组

java - 哈希漏洞

javascript - 检测鼠标事件上的多个重叠 SVG 形状元素

除非使用 setTimeout(),否则 JavaScript 重定向 (location.href) 会破坏后退按钮

javascript - 重写 nsIWindowWatcher 组件