如何使用 JavaScript 獲取當前 URL?


可以使用 `window.location` 物件獲取當前 URL。

  • `window.location.href` 屬性返回當前頁面的 href(URL)。我們也可以使用 `window.location` 或 `location` 代替 `window.location.href`。

我們還可以使用 `document.documentURI` 和 `document.URL` 屬性。

  • `document.documentURI` 返回文件的位置,以字串形式表示。

  • `document.URL` 返回文件的 URL,以字串形式表示。

讓我們透過程式示例瞭解如何使用上述屬性使用 JavaScript 獲取當前 URL。

示例 1 - 使用 `window.location.href` 屬性。

在這個示例中,我們使用 `window.location.href` 獲取當前 URL。在下面的示例中,您可以嘗試使用 `window.location` 或 `location` 代替 `window.location.href`。

<html>
   <body>
      <div>
         <p id ="dd"></p>
      </div>
      <script type="text/javascript">
         var iid=document.getElementById("dd");
         alert(window.location.href);
         iid.innerHTML = "URL is " + window.location.href;
      </script>
   </body>
</html>

輸出

我們線上執行程式碼。當您執行上述程式碼時,會顯示一個顯示當前頁面 URL 的警報訊息。此外,瀏覽器還會顯示頁面的當前 URL。

URL is https://tpcg1.tutorialspoint.com/root/84804/index.htm?v=1

上述 URL 是 hello.html 檔案的位置地址。根據您儲存 hello.html 檔案的位置,您可能會得到不同的 URL。在本地執行程式時,您也可能會得到不同的 URL 型別。

當您在本地執行程式時,您可能會得到類似於以下內容的當前 URL -

URL is file:///D:/JavaScript/index.html

我將 index.html 檔案儲存在 D:/JavaScript 目錄中。

示例 2 - 使用 `document.documentURI`

在這個示例中,我們使用 `document.documentURI` 獲取文件的當前 URL。

<html>
   <body>
      <div>
         <p id ="dd"></p>
      </div>
      <script type="text/javascript">
         var iid=document.getElementById("dd");
         alert(document.documentURI);
         iid.innerHTML = "URL is " + document.documentURI;
      </script>
   </body>
</html>

輸出

我們線上執行程式碼。當您執行上述程式碼時,會顯示一個顯示文件當前 URL 的警報訊息。此外,瀏覽器還會顯示文件的當前 URL。

URL is https://tpcg1.tutorialspoint.com/root/59223/index.htm?v=1

與示例 1 相同,上述 URL 是 hello.html 檔案的位置地址。根據您儲存 hello.html 檔案的位置,您可能會得到不同的 URL。在本地執行程式碼時,您也可能會得到不同的 URL 型別。

示例 3 - 使用 `document.URL`

在這個示例中,我們使用 `document.URL` 獲取文件的當前 URL。

<html>
   <body>
      <div>
         <p id ="dd"></p>
      </div>
      <script type="text/javascript">
         var iid=document.getElementById("dd");
         alert(document.URL);
         iid.innerHTML = "URL is " + document.URL;
      </script>
   </body>
</html>

輸出

當您執行上述程式碼時,會顯示一個顯示文件當前 URL 的警報訊息。此外,瀏覽器還會顯示當前 URL。

URL is https://tpcg1.tutorialspoint.com/root/24466/index.htm?v=1

更新於: 2022年4月20日

1K+ 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告