【问题标题】:Firefox automatically decoding encoded parameter in url, does not happen in IEFirefox 自动解码 url 中的编码参数,在 IE 中不会发生
【发布时间】:2011-06-17 16:08:26
【问题描述】:

我对 Firefox 和 IE 感到沮丧,主要是 Firefox,因为它会在我可以在 Javascript 中使用它之前自动解码散列中的参数。 IE 不会自动解码 url,因此不会给我阅读错误。

我的问题和这个类似,只是我没有使用 ASP.NET ASP.NET MVC automatically decoding JSON-encoded parameters from AJAX

所以,如果我采用像 example.com/#question=!%40%23%24%25^%26*( 这样的网址

而 "!%40%23%24%25^%26*(" 是使用 encodeURIComponent 编码的,但在 IE 中,当我访问哈希时,它将保留为 "!%40%23%24%25^% 26*(",但是在Firefox中,当我访问哈希时,它会自动解码为"!@#$%^&*("

问题在于,在我的脚本中,我使用 decodeURIComponent 来解码编码值,如果字符串确实被编码,这很好。由于它已经在 Firefox 中解码,它给我一个格式错误的 URI 序列错误,而 IE 根本没有给我任何错误。

我该如何解决这个问题?

【问题讨论】:

    标签: javascript ajax encoding encodeuricomponent


    【解决方案1】:

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

    【讨论】:

    • 非常感谢。我刚刚在 Fx 中遇到了同样的问题(Chrome 很好)并且 location.href.split("#!")[1] 也对我有用。
    • 似乎 Firefox 也不会很快解决这个问题。自 2002 年以来,他们一直在讨论这个错误 :( bugzilla.mozilla.org/show_bug.cgi?id=135309bugzilla.mozilla.org/show_bug.cgi?id=483304
    • Firefox 允许在哈希字符串中使用“#”,因此window.location.hash.split("#").splice(1).join("#") 可能更安全。
    【解决方案2】:

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

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

    确实 window.location.href.split("#!")[1] 不会被 FF 自动解码(至少今天是这样)。

    【讨论】:

    • window.location.hash 实际上是问题的根源,所以这行不通。但这就是它应该...
    【解决方案3】:

    上述答案有效,但您的网址包含多个 # 的情况除外。这应该处理所有情况:

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

    此外,这似乎应该很快在 Firefox 中得到修复。只是打夜间:

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

    【讨论】:

      【解决方案4】:

      我遇到了这个问题。我用这个解决方案解决了它:

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

      【讨论】:

        【解决方案5】:

        这是一个非常古老的问题,但根本问题仍未解决。 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));
        

        你怎么看?

        【讨论】:

          猜你喜欢
          • 2019-06-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-07-26
          • 2020-10-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多