在JavaScript中获取当前页面的域名(包括协议部分,如http
或https
),可以通过window.location
对象来实现。window.location
对象包含了当前文档的URL信息。
window.location
对象获取域名,无需复杂的逻辑处理。window.location
对象都会更新,确保获取到的域名是最新的。window.location
对象,具有良好的兼容性。window.location
对象包含多个属性,其中常用的有:
window.location.href
:完整的URL。window.location.protocol
:URL的协议部分(如http:
或https:
)。window.location.host
:主机名和端口号(如www.example.com:80
)。window.location.hostname
:主机名(如www.example.com
)。window.location.port
:端口号(如80
)。// 获取完整的URL
console.log(window.location.href);
// 获取协议部分(包括http或https)
console.log(window.location.protocol);
// 获取主机名和端口号
console.log(window.location.host);
// 获取主机名
console.log(window.location.hostname);
// 获取端口号
console.log(window.location.port);
http:
或https:
前缀?原因:window.location.protocol
返回的协议部分不包含冒号(:
)。
解决方法:
const protocol = window.location.protocol + '//';
console.log(protocol); // 输出 http:// 或 https://
原因:可能是由于页面被重定向到了不同的域名,或者在不同的子域名下访问。
解决方法:
确保在获取域名之前,页面已经完全加载,并且没有被重定向。可以通过window.onload
事件来确保:
window.onload = function() {
console.log(window.location.href);
};
通过以上方法,可以准确获取当前页面的域名及其协议部分,并解决常见的相关问题。
领取专属 10元无门槛券
手把手带您无忧上云