【问题标题】:Special characters in url in SafariSafari中url中的特殊字符
【发布时间】:2017-03-07 17:12:49
【问题描述】:

我们在 Web 应用程序中使用了一些特殊字符,例如:example.com/foo#вап

我们使用decodeURI(window.location.hash) 解析哈希(有时哈希包含未编码的特殊字符)并设置新值,如window.location.hash = "вап"

在 Chrome、Firefox、Opera 甚至 IE 中一切正常,但在 Safari 中我们得到 20? 而不是 вап

如果在 Safari 中像 window.location.hash = encodeURI("вап"); 这样设置哈希值,它可以工作,但当然它在 Chrome、FF 等中不起作用。

【问题讨论】:

  • 我在 iOS-6.1.6 (iPod) 和 iOS-7.1.1 (iPad) 上的 Mobile Safari 中也看到了同样的异常行为。

标签: safari uri special-characters


【解决方案1】:

我终于找到了解决方案。 如果通过window.location.href 设置哈希,一切正常。

代码如下:

var newHash = ...
var sharpIdx = window.location.href.indexOf("#");
if (sharpIdx === -1) {
  window.location.href = window.location.href + "#" + newHash;
} else {
  window.location.href = window.location.href.substr(0, sharpIdx) + "#" + newHash;
}

【讨论】:

  • 因此不仅访问location.href 以读取片段比读取location.hash 更可靠(因为Mozilla 处理读取location.hash 错误),而且写入它以进行哈希更新更可靠,因为苹果浏览器。很高兴知道。这是一个更容易编写代码的解决方案,而不是在将代码分配给 location.hash 之前修复我的代码以在正确的部分上调用 encodeURIComponent()...
【解决方案2】:

我遇到了同样的问题,找到了另一种解决方法

window.location.hash = path;
// For safari url change fix
if (window.location.hash !== path) {
    window.location.hash = encodeURI(path);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-21
    • 2015-10-21
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 2014-06-19
    • 2021-07-16
    相关资源
    最近更新 更多