【问题标题】:Get the text fragment part of current URL from window.location从 window.location 获取当前 URL 的文本片段部分
【发布时间】:2021-07-06 10:15:36
【问题描述】:

我想为任何使用text fragment 链接访问我的网站的人提供自定义布局。

例如。 https://en.wikipedia.org/w/index.php?title=Cat&oldid=916388819#:~:text=Claws-,Like%20almost,the%20Felidae%2C,-cats

:~: 之后的部分将是文本片段。我想得到那部分。

我试过window.location.hrefwindow.location.hash。但 window.location.href 只返回没有text fragment 的url,而window.location.hash 返回一个空字符串。

要复制此访问https://en.wikipedia.org/w/index.php?title=Cat&oldid=916388819#:~:text=Claws-,Like%20almost,the%20Felidae%2C,-cats,将其复制并粘贴到新选项卡,并尝试从window.location 获取文本片段(markdown 链接似乎与文本片段有问题)。

那么还有其他方法可以获取地址栏中的文本片段部分吗?

【问题讨论】:

  • .hash 将包含它
  • 我在 Firefox 和 chrome 中都试过了。它似乎没有包含。 window.location.hash 只返回一个空字符串。在那个维基百科页面上window.location.hash 对你有用吗?
  • yes,你是怎么执行的?
  • 它有哈希但我不知道为什么直接从markdown链接点击时文本片段不起作用。单击降价链接时,它会打开维基百科,但也不会选择文本片段所针对的文本。所以请从这里复制粘贴https://en.wikipedia.org/w/index.php?title=Cat&oldid=916388819#:~:text=Claws-,Like%20almost,the%20Felidae%2C,-cats打开链接,然后尝试获取哈希

标签: javascript google-chrome url browser


【解决方案1】:

您可以通过performance.getEntriesByType("navigation")[0].name 获取文本片段(您可以运行正则表达式来获取实际值,例如performance.getEntriesByType("navigation")[0].name.split('#:~:text=')[1] [但您可能希望使其更加宽容和防错])。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2013-10-27
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    相关资源
    最近更新 更多