window.location.hash issue in Firefox

六眼飞鱼酱① 提交于 2019-12-05 10:24:47

A workaround is to use

window.location.toString().split('#')[1] // car=Town%20%26%20Country

Instead of

window.location.hash.substring(1);

May I also suggest a different method (looks simpler to understand IMHO)

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

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

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

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:

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!