document.write(document.URL)
document.URL 會回傳目前頁面的完整網址字串,直接印在頁面上即可看到結果。
它的價值在於:在完全沒有任何伺服器端技術的情況下,仍能透過網址把資訊傳進頁面。做法是這樣——在網址列輸入 https://你的網址#書籤名稱,頁面中的程式讀取 document.URL 後就能取得那個書籤部分,據此決定要顯示什麼內容。
這其實是「片段識別字」(hash)最經典的用法。相比查詢字串,hash 有個關鍵優勢:改動 hash 不會重新整理頁面,因此特別適合用於頁內導航與單頁應用的狀態記錄。
除了 document.URL,更常用的是 location 物件。它把一條完整網址拆開給你:
// 假設目前網址是 https://www.example.com/page.htm?id=5#sec2
location.href // 完整網址
location.protocol // "http:"
location.host // "www.example.com"
location.hostname // "www.example.com"(不含 port)
location.port // ""(未指定連接埠時)
location.pathname // "/page.htm"
location.search // "?id=5"
location.hash // "#sec2"
實務上讀 hash 通常會這樣寫:
var hash = location.hash.substring(1); // 去掉開頭的 '#'
if (hash) {
document.getElementById(hash).scrollIntoView();
}
document.URL 與 location.href 在大多數情況下回傳相同內容。差別在於 location 除了讀取,還可以寫入來觸發跳轉,並提供分解後的各個片段。因此建議以 location 為主要工具,document.URL 則是唯讀的便利寫法。
讀取 hash 時記得,它是使用者可控的輸入值。若你打算把 hash 內容直接插入頁面,請務必先處理——用 encodeURIComponent 編碼後比對,或直接以 textContent 輸出,避免成為 XSS 的入口。