如何使用 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+ 次浏览

启动您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.