在 Web 開發中,經常需要獲取當前頁面的 URL 資訊,例如完整網址、域名、路徑、查詢參數等。JavaScript 提供了多種屬性和方法來獲取這些資訊,但初學者常感到困惑。本文將系統整理 document.URL、location.href、self.location.href 等常用屬性的差異,並提供實用的代碼示例。
| 屬性 | 說明 | 典型輸出範例 |
|---|---|---|
document.URL | 當前文檔的完整 URL(唯讀) | https://example.com/path/page.html?query=1 |
document.location.href | 同 location.href,完整 URL,可讀寫 | https://example.com/path/page.html?query=1 |
self.location.href | 當前視窗的完整 URL | https://example.com/path/page.html?query=1 |
document.location | 返回 Location 物件,可進一步取得 protocol、host、pathname 等 | Location {href: "...", protocol: "https:", ...} |
top.location.href | 最頂層視窗的 URL(跨 iframe 時有用) | https://top-example.com/ |
parent.document.location | 父視窗的 URL | https://parent-example.com/ |
location.hostname | 當前頁面的域名(不含端口) | example.com |
top.location.hostname | 最頂層視窗的域名 | top-example.com |
下面的代碼可直接放入頁面中,會在頁面上輸出一張表格,顯示所有常見 URL 相關屬性的值:
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<script>
var thisURL = document.URL;
var thisHREF = document.location.href;
var thisSLoc = self.location.href;
var thisDLoc = document.location;
var strwrite = "<tr><td valign='top'>thisURL: </td><td>[" + thisURL + "]</td></tr>";
strwrite += "<tr><td valign='top'>thisHREF: </td><td>[" + thisHREF + "]</td></tr>";
strwrite += "<tr><td valign='top'>thisSLoc: </td><td>[" + thisSLoc + "]</td></tr>";
strwrite += "<tr><td valign='top'>thisDLoc: </td><td>[" + thisDLoc + "]</td></tr>";
document.write(strwrite);
</script>
</table>
<script>
var thisTLoc = top.location.href;
var thisPLoc = parent.document.location;
var thisTHost = top.location.hostname;
var thisHost = location.hostname;
var strwrite2 = "<tr><td valign='top'>thisTLoc: </td><td>[" + thisTLoc + "]</td></tr>";
strwrite2 += "<tr><td valign='top'>thisPLoc: </td><td>[" + thisPLoc + "]</td></tr>";
strwrite2 += "<tr><td valign='top'>thisTHost: </td><td>[" + thisTHost + "]</td></tr>";
strwrite2 += "<tr><td valign='top'>thisHost: </td><td>[" + thisHost + "]</td></tr>";
document.write(strwrite2);
</script>
<script>
// 獲取當前頁面文件名
var tmpHPage = thisHREF.split("/");
var thisHPage = tmpHPage[tmpHPage.length - 1];
var tmpUPage = thisURL.split("/");
var thisUPage = tmpUPage[tmpUPage.length - 1];
var strwrite3 = "<tr><td valign='top'>thisHPage: </td><td>[" + thisHPage + "]</td></tr>";
strwrite3 += "<tr><td valign='top'>thisUPage: </td><td>[" + thisUPage + "]</td></tr>";
document.write(strwrite3);
</script>
若需進一步解析查詢字符串,可使用 URLSearchParams(現代瀏覽器支援)或手寫解析函數:
// 現代寫法
const params = new URLSearchParams(window.location.search);
console.log(params.get('id')); // 獲取 ?id=123 中的 123
// 兼容舊瀏覽器的簡易函數
function getQueryParam(name) {
const reg = new RegExp('[?&]' + name + '=([^&]*)');
const match = window.location.search.match(reg);
return match ? decodeURIComponent(match[1]) : null;
}
window.location.href 或 document.URL 即可滿足需求。location 物件的屬性(protocol、host、pathname、search、hash)。top.location 和 parent.location。掌握這些屬性,能讓你在處理頁面跳轉、參數傳遞、權限判斷等場景時遊刃有餘。