DIV CSS 佈局教程網

取得當前網址的各種寫法整理
編輯:JavaScript綜合知識     

同一個「目前網址」,JavaScript 提供了好幾種取法。它們大部分等價,但在 iframe 環境或需要拆出檔名的時候差別就出來了。

取得完整網址

thisURL = document.URL;
thisHREF = document.location.href;
thisSLoc = self.location.href;
thisDLoc = document.location;

這四個在一般情況下都會得到同一個字串。self 指向目前的視窗,與 window 等價,寫 self.location.href 只是風格差異。

取得上層視窗的網址

thisTLoc = top.location.href;              // 最頂層視窗
thisPLoc = parent.document.location;       // 直接父視窗
thisTHost = top.location.hostname;         // 頂層的網域
thisHost = location.hostname;              // 目前視窗的網域

在 iframe 結構中這幾個值會不同。要注意跨來源限制:若 iframe 與外層頁面不同源,存取 top.location 會丟出安全性錯誤。同源的情況下才讀得到。

拆出檔名

tmpHPage = thisHREF.split("/");
thisHPage = tmpHPage[tmpHPage.length - 1];

tmpUPage = thisURL.split("/");
thisUPage = tmpUPage[tmpUPage.length - 1];

用斜線切開後取最後一段,就是檔名部分。但若網址帶有查詢參數,檔名會連 ?foo=1 一起被切出來。

用視窗輸出對照結果

<table>
<script language="javascript">
var str = "";
str += "<tr><td>thisURL:  </td><td>[" + document.URL + "]</td></tr>";
str += "<tr><td>thisHREF: </td><td>[" + document.location.href + "]</td></tr>";
str += "<tr><td>thisSLoc: </td><td>[" + self.location.href + "]</td></tr>";
document.write(str);
</script>
</table>

現代做法:用 URL 物件

字串切字總是容易出錯。URL 與 URLSearchParams 已經把各部位拆好了:

const url = new URL(location.href);

url.href;          // 完整網址
url.origin;        // https://example.com
url.protocol;      // https:
url.hostname;      // example.com
url.port;          // 8080
url.pathname;      // /path/page.html
url.search;        // ?foo=1&bar=2
url.hash;          // #section

取檔名也變得乾淨:

const fileName = url.pathname.split('/').pop();     // page.html
const page = url.searchParams.get('page');          // 查詢參數

一個安全提醒

若要把 location.href 的內容輸出到畫面上,不能直接塞進 innerHTML。網址可能包含 <script> 之類的字元,一旦被解析就會執行。請用 textContent,或先做 HTML 編碼。同理,若要用 location.href 作為後續跳轉的依據,記得先驗證來源,避免開放重新導向漏洞。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved