【问题标题】:document.location.hash not working in Safaridocument.location.hash 在 Safari 中不起作用
【发布时间】:2021-01-28 18:07:48
【问题描述】:

我正在使用 $postMessage 与父窗口进行跨浏览器通信。 除 Safari 外,所有浏览器都可以正常工作。问题是使用 document.location.hash 哈希在 Safari 中返回为空。 无论如何,这发生在 Safari 中。

function postMessage( msg ){  
  var parent_url = decodeURIComponent( document.location.hash.replace( /^#/, '' ) );
    $.postMessage({ method:'resize', message:msg}, parent_url, parent );
} 

更新:

因此,父窗口正在创建一个 Iframe,该 Iframe 将 '#url 附加到它的末尾。我正在使用 document.location.hash.replace( /^#/, '' ) 来获取该 url 以用作 postMessage 的 url。在 Safari V8.0.2 中测试所有这些时,Safari 删除了 # 和 # 之后的任何内容。所以我的 parent_url 返回空白。

解决方案是在 url 末尾使用 &param=url 而不是 #。 我不确定为什么 Safari 会删除 # 或者它是否是一个有据可查的问题。我一直在网上搜索以了解更多信息。

【问题讨论】:

  • 不工作以什么方式?抛出错误?
  • window.location.hash,不要使用document
  • document.location.hash 在 safari 中返回为空
  • 那么把它改成window有什么不同吗?
  • window 在 safari 中产生相同的结果。

标签: javascript jquery safari postmessage


【解决方案1】:

如果location.hash 不可用,为什么不使用location.href

href    = location.href;
hashIdx = href.lastIndexOf('#');
hash    = href.slice(hashIdx);

// or in one line
hash = location.href.slice(location.href.lastIndexOf('#'))

注意hash在不少浏览器中是不支持的:https://developer.mozilla.org/en-US/docs/Web/API/URLUtils.hash

【讨论】:

  • MDN 链接指向不同的 API,请参阅 developer.mozilla.org/en-US/docs/Web/API/Location 主要问题很可能是尝试使用 documetn 而不是 window
  • # 从 Safari 的 url 中删除。
  • 刚刚在 Safari 中访问了 stackoverflow.com/questions/28077188/…,我的代码返回了 "#tab-top" - 话虽如此,我的 Safari 版本也有一个带有 hashLocation 对象。您使用的是什么版本的 Safari?
  • 我使用的是 8.0.2 版。
  • 这在 Firefox 51.0.1 和 Safari 10.0.3 中非常适合我。干得好
【解决方案2】:

刚刚在旧 iPad 上使用 Safari 也遇到了这个问题,我无法在 iOS 12.5.1 之后更新。我有一个使用 Spotify 隐式授权进行授权的小型 Web 应用程序。 Spotify 在哈希片段 (#access_token...) 中返回访问令牌,附加到我的重定向 URI。这在这个旧 iPad 上的所有浏览器中都可以正常工作,但 Safari 除外。 Safari 在较新版本的 iOS 中运行良好。因此,我使用 Mac 上的 Web Inspector 将 Safari 连接到我的 iPad,发现 document.location.hash 和 window.location.hash 都是空的。所以似乎没有办法让旧 iOS 版本上的 Safari 使用任何在重定向回时使用哈希片段的 API(如 Spotify 隐式授权)。

【讨论】:

    猜你喜欢
    • 2019-01-08
    • 2019-07-12
    • 2013-08-17
    • 2015-05-12
    • 2012-12-15
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多