在JavaScript中,获取当前页面的网址可以通过多种方式实现。以下是一些常用的方法:
以下是一些获取当前页面网址的示例代码:
var fullUrl = window.location.href;
console.log(fullUrl); // 输出: http://example.com/path/to/page.html?query=string#hashvar protocol = window.location.protocol;
console.log(protocol); // 输出: http: 或 https:var hostname = window.location.hostname;
console.log(hostname); // 输出: example.comvar port = window.location.port;
console.log(port); // 输出: 80 或其他端口号,如果没有指定端口则返回空字符串var pathname = window.location.pathname;
console.log(pathname); // 输出: /path/to/page.htmlvar search = window.location.search;
console.log(search); // 输出: ?query=stringvar hash = window.location.hash;
console.log(hash); // 输出: #hash问题: 在某些情况下,window.location.href可能返回不完整的URL或包含意外的字符。
原因: 可能是由于浏览器缓存、重定向或JavaScript执行环境的影响。
解决方法:
function cleanUrl(url) {
var parser = document.createElement('a');
parser.href = url;
return parser.href; // 这将解析并返回一个规范化的URL
}
var cleanedUrl = cleanUrl(window.location.href);
console.log(cleanedUrl);通过上述方法,可以有效获取和处理当前页面的网址信息。