調試時經常需要確認「當前到底是哪個地址、哪個路徑、哪個域名」,而這類信息散落在好幾個對象上,名字又極其相似,很容易記混。下面做個集中整理。
console.info("document.URL=" + document.URL);
console.info("document.location.href=" + document.location.href);
// console.info("document.base=" + document.base); 這是錯的!
console.info("document.location=" + document.location);
console.info("self.location.href=" + self.location.href);
console.info("top.location.href=" + top.location.href);
console.info("location.hostname=" + location.hostname);
console.info("window.location.host=" + window.location.host);
console.info("window.location.pathname=" + window.location.pathname);
document.URL —— 目前頁面的完整 URL,只讀屬性。
document.location 與 window.location —— 實際上是同一個 Location 對象,指向當前窗口的 URL 信息,既可以讀也可以寫(賦值即跳轉)。
self.location.href —— self 始終指向當前窗口自身,在普通頁面中等價於 window。
top.location.href —— 指向最頂層的瀏覽器窗口。頁面沒有被嵌套在 frame 裡時,它等於 window.location.href;若頁面被嵌在 iframe 中,它就指向外層頁面。要注意跨域情況下讀取 top.location 會拋出安全錯誤。
location.hostname —— 只有主機名,例如 www.example.com,不含端口。
location.host —— 主機名加端口,例如 www.example.com:8080。這是兩者唯一的差別,也是最容易踩的地方。
location.pathname —— 只取路徑部分,例如 /article/123.html,不含協議、域名與查詢串。
至於示例中被註釋掉的 document.base,它並不是標準屬性,取到的是 undefined。若確實需要頁面基準 URL,應該讀 document.baseURI,它會正確反映 <base href> 標籤的影響。
· location.protocol —— 協議,如 https:。
· location.search —— 查詢串,含問號,如 ?id=1&page=2。
· location.hash —— 錨點,含井號。
· location.origin —— 協議 + 域名 + 端口,做同源判斷時最方便。
· document.referrer —— 來源頁面的地址,流量分析常用。
把這幾個記牢,日常排查 URL 相關問題基本夠用了。