Firefox中window.location.hash问题

5

Consider the following code:

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在这里有些奇怪,导致它解析的“car”参数实际是“Town”,而不是国家。

是否存在安全的方法可以跨浏览器解析哈希参数,或者修复Firefox的解析方式?


注意:此问题仅限于Firefox对哈希参数的解析。当使用查询字符串运行相同的测试时:

queryString = window.location.search.substring(1);
alert('Query String = '+queryString);

all browsers will show:

car=Town%20%26%20Country


1
作为一个侧面的注释:这实际上是Firefox中的一个错误。 - user123444555621
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;
}

测试用例

网址 = https://dev59.com/LFvUa4cB1Zd3GeqPpgxn color=red?qs1=two&qs2=anything


(注:该网址包含特殊字符,需进行编码处理)
getHashParams() // returns {"car type": "Town & Country", "car color": "red"}

使用window.location.toString().split('#')[1]代替location.hash对我非常有效。这是一个恶意的问题,谢谢。 - Yarin

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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接