5

考虑以下代码:

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

使用以下哈希运行时:

#car=城镇%20%26%20国家

ChromeSafari中的结果将是:

汽车=城镇%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国家

4

2 回答 2

7

一种解决方法是使用

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

测试用例

网址 =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"}
于 2011-09-07T18:10:37.367 回答
0

window.location.toString().split('#')[1]在大多数情况下都可以使用,但如果哈希包含另一个哈希(编码或其他方式)则不会。

换句话说split('#'),可能会返回一个长度>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
}
于 2013-11-27T23:32:30.017 回答