在JavaScript中,获取当前页面的URL可以通过多种方式实现。以下是一些常用的方法:
window.location.href
这是最直接的方法,返回整个URL字符串。
let currentUrl = window.location.href;
console.log(currentUrl);
window.location.pathname
如果你只需要获取URL中的路径部分(不包括协议、域名和查询字符串),可以使用这个属性。
let pathName = window.location.pathname;
console.log(pathName);
window.location.search
这个属性返回URL中"?"后面的部分,即查询字符串。
let queryString = window.location.search;
console.log(queryString);
window.location.origin
这个属性返回URL的协议、主机名和端口号。
let origin = window.location.origin;
console.log(origin);
如果你不需要片段标识符(即URL中"#"后面的部分),可以使用以下方法去除:
let cleanUrl = window.location.href.split('#')[0];
console.log(cleanUrl);
window.location
可能不可用例如,在某些服务器渲染的环境中,window
对象可能不存在。这时,你可以使用条件判断来避免错误:
if (typeof window !== 'undefined') {
let currentUrl = window.location.href;
console.log(currentUrl);
} else {
console.log('window object is not available');
}
通过这些方法,你可以灵活地获取和处理当前页面的URL,以适应不同的应用需求。
领取专属 10元无门槛券
手把手带您无忧上云