JavaScript 如何获取当前URL
在本文中,我们将了解如何获取当前网页或网站的网址。可以通过使用文档对象的URL属性来获取当前URL。URL属性返回一个字符串,其中包含了当前页面的完整位置,并且包含了HTTP协议的字符串(例如http://)。
我们可以用两种方式来获取当前URL:
- Document.URL: DOM的URL属性用于返回一个包含当前文档完整URL的字符串。该字符串还包含了HTTP协议(例如http://)。
- window.location.href: window.location.href返回当前文档的完整URL,包括HTTP协议。
Document.URL: DOM的URL属性用于返回一个包含当前文档完整URL的字符串。该字符串还包含了HTTP协议(例如http://)。
语法:
document.URL
返回值: 它返回一个字符串值,表示文档的完整URL。
示例1: 此示例演示如何获取网页的当前URL。
<!DOCTYPE html>
<html>
<head>
<title>
How to get the current URL using JavaScript ?
</title>
</head>
<body>
<h1 style="color:green">GeeksforGeeks</h1>
<h2>
JavaScript: Program to
get the website URL ?
</h2>
<p>
<b>
Click on Below Button
To Get Current URL
</b>
</p>
<button onclick="GetURL()">
Get URL
</button>
<p id="url"></p>
<script>
function GetURL() {
var gfg = document.URL;
document.getElementById("url").innerHTML = gfg;
}
</script>
</body>
</html>
输出:
window.location.href : HTML DOM Window.location属性返回一个包含有关文档当前位置信息的Location对象。
语法:
window.location.href
示例2: 此样例演示如何获取当前网页的URL。
<!DOCTYPE html>
<html>
<head>
<title>
How to get the current URL using JavaScript ?
</title>
</head>
<body>
<h1 style="color:green">
GeeksforGeeks
</h1>
<h2>
JavaScript: Program to
get the website URL ?
</h2>
<p>
<b>
Click on Below Button
To Get Current URL
</b>
</p>
<button onclick="GetURL()">
Get URL
</button>
<p id="url"></p>
<script>
function GetURL() {
var gfg = window.location.href;
document.getElementById("url").innerHTML = gfg;
}
</script>
</body>
</html>
输出: