[英]Get the text fragment part of current URL from window.location
我想為任何使用文本片段鏈接訪問我的網站的人提供自定義布局。
例如。 https://en.wikipedia.org/w/index.php?title=Cat&oldid=916388819#:~:text=Claws-,Like%20almost,the%20Felidae%2C,-cats
這里:~:
之后的部分將是文本片段。 我想得到那個部分。
我試過window.location.href
和window.location.hash
。 但是window.location.href
只返回 url 沒有text fragment
,而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 鏈接似乎與文本片段有問題)。
那么有沒有其他方法可以在地址欄中獲取文本片段部分?
window.location.href
和window.location.hash
自 Z9E13B69D1D2DA9327102 誕生之日起就一直在工作,並且表現完全符合您的預期。
最近的變化改變了片段行為,而不是像往常一樣工作。 如果:~:
出現在 URL 中,Chrome 現在將刪除 URL 的部分內容。
正如@DenverCoder9 指出的那樣,唯一能保證整個 URL 的方法,應該是一個基本而簡單的操作,現在只能通過performance
API 在 Chrome 中完成, performance.getEntriesByType("navigation")[0].name
這個過去可以通過window.location.href
和window.location.hash
完成的基本操作不再可能。
Chrome 需要performance.getEntriesByType("navigation")[0].name
與window.location.href
相比,這樣的基本操作是愚蠢的。 我們希望 Chrome 關於:~:
的新行為得到糾正。 這種“刪除部分 URL”的新行為是史無前例的,被認為是有害的。
相關,請參閱問題:
關鍵詞:“文本片段”、“片段指令”
您可以通過performance.getEntriesByType("navigation")[0].name
獲取文本片段(您可以運行正則表達式來獲取實際值,例如performance.getEntriesByType("navigation")[0].name.split('#:~:text=')[1]
[但你可能想讓它更寬容和更抗錯])。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.