JavaScript - 获取当前 URL
在 JavaScript 中,我们可以使用 window.location 对象获取页面的当前 URL。window.location 对象包含有关页面当前 URL 的信息。
我们也可以通过另一个方法获取 URL,即 document.URL。另一个方法是 document.documentURI,它以字符串形式返回文档的位置。
使用 window.location
可以使用 window.location 对象获取当前 URL。window.location.href 属性返回当前页面的 href(URL)。我们也可以使用 window.location 或 location 代替 window.location.href。
示例
在此示例中,我们将使用 window.location.href 获取当前 URL。在下面的示例中,您可以尝试使用 window.location 或 location 代替 window.location.href。
<html>
<body>
<p id="demo"></p>
<script>
let currentURL = window.location.href;
document.getElementById("demo").innerHTML = currentURL;
</script>
</body>
</html>
输出
我们在线执行代码。运行上述代码后,您将看到包含当前 URL 的控制台消息。
https://www.cainiaomax.com/javascript/javascript_get_current-url.php
使用 document.URL
我们也可以使用 document.documentURI 和 document.URL 属性。document.URL 以字符串形式返回文档的 URL。
示例
在此示例中,我们将使用 document.URL 获取文档的当前 URL。
<html>
<body>
<p id="demo"></p>
<script>
let currentURL = document.URL;
document.getElementById("demo").innerHTML = currentURL;
</script>
</body>
</html>
输出
执行上述代码后,控制台中将显示当前 URL。
https://www.cainiaomax.com/javascript/javascript_get_current_url.php
使用 document.documentURI
document.documentURI 以字符串形式返回文档的位置。
示例
在此示例中,我们将使用 document.documentURI 获取文档的当前 URL。
<html>
<body>
<p id="demo"></p>
<script>
let currentURL = document.documentURI;
document.getElementById("demo").innerHTML = currentURL;
</script>
</body>
</html>
输出
执行上述代码后,您将在控制台中看到文档的当前 URL。
https://www.cainiaomax.com/javascript/javascript_get_current_url.php

