window.location 方法获取URL

266 阅读1分钟

示例

https://www.baidu.com:8080/windows/location/page.html?vid=1&id=xjq#tip
1、【pathname】 设置或获取对象指定的文件名或路径
console.log(window.location.pathname)
//输出: "/windows/location/page.html"
2、【href】设置或获取整个 URL 为字符串
console.log(window.location.href)
//输出: "https://www.baidu.com:8080/windows/location/page.html?vid=1&id=xjq#tip"
3、【port】设置或获取与 URL 关联的端口号码
console.log(window.location.port)
//输出: "8080"
4、【protocol】设置或获取 URL 的协议部分(http:或https)
console.log(window.location.protocol)
//输出: "https:"
5、【hash】设置或获取 href 属性中在井号“#”后面的分段
console.log(window.location.hash)
//输出: "#tip"
6、【host】设置或获取 location 或 URL 的 hostname 和 port 号
console.log(window.location.host)
//输出: "www.baidu.com:8080"
7、【hostname】设置或获取 URL 的 hostname (域名)
console.log(window.location.hostname)
//输出: "www.baidu.com"
8、【search】设置或获取 href 属性中跟在问号后面的部分
console.log(window.location.search)
//输出: "?vid=1&id=xjq"
9、【origin】站点主地址(协议+主机名+端口)
console.log(window.location.origin)
//输出: "https://www.baidu.com:8080"