在瀏覽器開發中,經常需要取得目前頁面的網址、主機名稱、路徑或查詢參數等資訊。JavaScript 可以透過 document、location、window 等物件來完成這些操作。以下整理幾個常用寫法。
console.info('document.URL=' + document.URL);
console.info('document.location.href=' + document.location.href);
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.href:取得目前頁面位置,通常與 document.URL 相近。self.location.href:self 通常指目前視窗,因此可取得目前視窗的網址。top.location.href:取得最上層視窗的網址,在 iframe 場景中特別有用。location.hostname:取得主機名稱,例如 www.example.com。window.location.host:取得主機名稱與連接埠。window.location.pathname:取得目前路徑。有些開發者可能會嘗試使用 document.base,但這並不是標準且通用的屬性。若需要取得目前文件基礎 URI,較建議使用 document.baseURI 或 location 相關屬性。
此外,若需要取得查詢字串,可以使用 location.search;若需要取得 hash 片段,可以使用 location.hash。
console.log(location.search); // ?id=1&name=abc
console.log(location.hash); // #section
取得目前網址與位置資訊是前端開發中非常基礎但實用的能力。熟悉 location、window.location 與 document 的相關屬性,能幫助我們處理路由判斷、參數解析、頁面跳轉與 iframe 溝通等常見需求。