URL 是統一資源定位符(Uniform Resource Locator)。一個完整的 URL 由以下幾個部分組成:
scheme://host:port/path?query#fragment
& 分隔,參數名與值以 = 分隔。以這個 URL 為例:
https://www.x2y2.com:80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere
用 JavaScript 的 window.location 就能把各個部分逐一取出:
| 屬性 | 含義 | 本例回傳值 |
|---|---|---|
| window.location.href | 完整的 URL 字串,也就是瀏覽器網址列顯示的內容 | https://www.x2y2.com:80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere |
| window.location.protocol | 協定部分 | http: |
| window.location.host | 主機部分(含連接埠) | www.x2y2.com |
| window.location.port | 連接埠 | ""(空字串) |
| window.location.pathname | 路徑部分,即檔案位址 | /fisker/post/0703/window.location.html |
| window.location.search | 查詢字串部分 | ?ver=1.0&id=6 |
| window.location.hash | 錨點 | #imhere |
這裡有個容易踩到的細節:port 即使網址上明確寫了 :80,瀏覽器也會回傳空字串——因為 80 是 http 的預設埠,被視為「等同沒寫」。同理,https 的 443 也是。判斷時不能假設有值就是自訂埠。
另外 search 拿到的是包含問號的完整字串,若要取值還得自己拆。若頁面同時有 hash 變化(例如單頁應用的路由),監聽 hashchange 事件會比定時輪詢 location.href 有效率得多。