最简单的方法是使用window.location.href
属性,它可以返回当前页面的完整URL地址。例如:
var currentURL = window.location.href;
console.log(currentURL); // 输出类似"https://example.com/page.html"的地址
另一种方法是使用document.URL
属性,它也可以返回当前页面的完整URL地址。与window.location.href
类似,但语法略有不同:
var currentURL = document.URL;
console.log(currentURL); // 输出类似"https://example.com/page.html"的地址
需要分别获取URL的不同部分(如协议、主机名、端口号等),可以使用new URL()
构造函数,它会返回一个URL对象,可以通过其属性访问URL的各个组成部分。例如:
var currentURL = new URL(window.location.href);
console.log(currentURL.protocol); // 输出"https:"
console.log(currentURL.hostname); // 输出"example.com"
console.log(currentURL.port); // 输出""(空字符串,表示使用默认端口)