Firefox自动解码URL中的编码参数,但IE不会发生这种情况。

18

我在Firefox和IE之间遇到了困惑,主要是在Firefox中,它会自动解码哈希参数,导致我无法在Javascript中使用它。而IE不会自动解码URL,因此不会给我阅读错误。

我的问题类似于这个问题,只是我没有使用ASP.NET:ASP.NET MVC自动解码来自AJAX的JSON编码参数

所以,如果我拿一个像example.com/#question=!%40%23%24%25^%26*(的URL,其中"!%40%23%24%25^%26*("是使用encodeURIComponent编码的,在IE中访问哈希时,它将保留为"!%40%23%24%25^%26*(",但在Firefox中访问哈希时,它会自动解码为"!@#$%^&*("

这个问题在于,在我的脚本中,我使用decodeURIComponent解码已编码的值,如果字符串确实被编码,那么这也是可以的。由于在Firefox中它已经被解码了,所以它会给我一个格式不正确的URI序列错误,而IE则根本不会给我任何错误。

我该如何解决这个问题?

5个回答

19

经过搜索,我发现这是一个跨浏览器问题,最好使用location.href.split("#")[1]而不是window.location.hash


非常感谢您。我在Fx(Chrome没问题)中遇到了同样的问题,location.href.split("#!")[1] 对我也起作用了。 - meloncholy
1
看起来Firefox也不打算很快修复这个问题。他们从2002年开始讨论这个错误 :( https://bugzilla.mozilla.org/show_bug.cgi?id=135309 和 https://bugzilla.mozilla.org/show_bug.cgi?id=483304 - gregers
Firefox 允许在哈希字符串中包含“#”,因此最好使用 window.location.hash.split("#").splice(1).join("#") 来使其更加健壮。 - fourthnen

1

这实际上是你想要使用的:

decodeURI(window.location.hash.substr(1))

实际上,window.location.href.split("#!")[1] 今天至少在FF中不会自动解码。


window.location.hash 实际上是问题的根源,所以这样做行不通。但这应该是正确的做法... - gregers

1

这是一个非常老的问题,但根本问题仍未解决。Firefox对一些东西进行了编码,而其他浏览器则没有。

出于沮丧,我不得不创建完全不同的方法,并使算法独立于字符串是否被编码。

我希望这个解决方案能够帮助那些需要它的人:

function encodeOnce(text) {
  var doubleEncoded = encodeURIComponent(text);
  // only dive into it if there are any encoded strings...
  if (doubleEncoded.indexOf('%') != -1) {
    // reverse replace all % signs
    doubleEncoded = doubleEncoded.replace(/%25/g, '%');
    // if this is not equal to the original string, ...
    if (doubleEncoded != text) {
      // ... that means there was something to encode
      text = doubleEncoded;
    }
  }
  return text;
}

那么你可以这样做:

solution = encodeOnce(window.location.hash.slice(1));

你觉得怎么样?


0

上面的答案是有效的,除非您的网址包含多个#。以下处理所有情况:

var hash = "";
var indexOfHash = location.href.indexOf("#");
if (indexOfHash > -1) {
    hash = location.href.substring(indexOfHash);
}

此外,看起来这个问题很快就会在 Firefox 中解决。只需使用Nightly版本即可:

https://bugzilla.mozilla.org/show_bug.cgi?id=378962


0

我曾经遇到过这个问题,但是我用了以下的解决方案:

var currentLocation = document.location.hash;
var decodedLocation = decodeURI(currentLocation);

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