window.location
是 JavaScript 中用于获取和设置浏览器地址栏 URL 的对象,能够进行页面跳转、获取当前 URL、重新加载页面等操作。它是 window
对象的一部分,提供了多种属性和方法来操作 URL 和浏览器行为。
- window.location.href
作用:返回当前页面的完整 URL,跳转自定义地址// 获取当前页面的 URL console.log(window.location.href); // https://xxx/page?pageId=1 // 设置新的 URL,跳转到百度 window.location.href = 'https://www.baidu.com/index.htm';
- window.location.hostname
作用:获取当前 URL 的主机名(不包括协议、端口和路径)//https://www.baidu.com/index.htm console.log(window.location.hostname) // www.baidu.com
- window.location.protocol
作用:获取当前 URL 的协议部分(如http:
或https:
)//https://www.baidu.com/index.htm console.log(window.location.protocol); // https:
-
window.location.port
作用:获取当前 URL 的端口号。如果没有指定端口,返回空字符串console.log(window.location.port); // 8080 (如果 URL 中指定了端口号)
- window.location.pathname
作用:获取当前 URL 的路径部分,不包括域名和查询参数//https://www.baidu.com/index.htm console.log(window.location.pathname); // /index.htm
- window.location.pathname
作用:获取当前 URL 的路径部分,不包括域名和查询参数//https://www.baidu.com/index.htm console.log(window.location.pathname); // /index.htm
- window.location.search
作用:获取当前 URL 的查询字符串部分(即?
后面的部分,包括查询参数)// https://xxx/page?pageId=1 console.log(window.location.search); // ?pageId=1
- window.location.search
作用:获取当前 URL 的查询字符串部分(即?
后面的部分,包括查询参数)// https://xxx/page?pageId=1 console.log(window.location.search); // ?pageId=1
- window.location.hash
作用:获取或设置当前 URL 的锚点部分(即#
后面的部分),用于页面内导航// https://xxx/page#section1 console.log(window.location.hash); // #section1
-
window.location.replace
作用:跳转到指定 URL,但不会在历史记录中添加当前页面。这意味着用户无法使用浏览器的后退按钮返回到当前页面
window.location.replace('https://www.baidu.com/index.htm')
-
window.location.reload
作用:刷新当前页面。如果传递
true
,则会强制从服务器重新加载页面(不使用缓存);否则,默认会使用缓存window.location.reload(); // 重新加载页面,使用缓存 window.location.reload(true); // 强制重新加载页面,不使用缓存
- window.location.origin
作用:获取当前页面的根域名部分(包括协议、主机名和端口)。它相当于将
protocol + hostname + port
拼接在一起// https://www.xxx.com:8080 console.log(window.location.origin); // https://www.xxx.com:8080