在网页开发中,有时候我们需要获取当前网页的地址,并将其打印到控制台或者页面上。JavaScript 提供了多种方法来实现这一功能。以下是一些常用的方法:
获取当前网页地址
1. 使用 window.location.href
window.location.href 属性可以获取当前网页的完整地址。这是一个非常直接的方法。
console.log(window.location.href);
2. 使用 document.URL
document.URL 属性同样可以获取当前网页的地址,与 window.location.href 的作用相同。
console.log(document.URL);
3. 使用 window.location.protocol
window.location.protocol 属性可以获取当前网页的协议(如 http 或 https)。
console.log(window.location.protocol);
4. 使用 window.location.host
window.location.host 属性可以获取当前网页的主机名和端口号。
console.log(window.location.host);
5. 使用 window.location.pathname
window.location.pathname 属性可以获取当前网页的路径。
console.log(window.location.pathname);
打印网页地址
获取到网页地址后,我们可以将其打印到控制台或者页面上。
打印到控制台
使用 console.log 函数可以将内容打印到浏览器的控制台。
console.log(window.location.href);
打印到页面上
如果需要将地址显示在页面上,可以使用 HTML 和 JavaScript。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="url"></div>
<script>
document.getElementById('url').innerText = window.location.href;
</script>
</body>
</html>
在上面的例子中,我们创建了一个 div 元素,并通过 JavaScript 将 window.location.href 的值设置为其 innerText 属性,从而将网页地址显示在页面上。
通过以上方法,你可以轻松地获取并打印当前网页的地址。这些方法在网页开发中非常实用,可以帮助你更好地了解当前网页的状态。
