JS获取和设置URL及参数

版权声明: https://blog.csdn.net/chenwuai/article/details/83176474

0x00 整个 URL 字符串

// 如果 URL 为 https://github.com/chenchenwuai?a=111&b=222
//获取
console.log(window.location.href)
//  输出  https://github.com/chenchenwuai?a=111&b=222

//设置
window.location.href= "https://github.com";
// 设置后网页跳转到 https://github.com

0x01 协议部分

// 如果 URL 为 https://github.com/chenchenwuai?a=111&b=222
//获取
console.log(window.location.protocol)
//  输出  https:

//设置
window.location.protocol= "http:";
// 设置后网页会进行跳转

0x02 hostname(或ip)和port端口

// 如果 URL 为 https://github.com/chenchenwuai?a=111&b=222
//获取
console.log(window.location.host)
//  输出  github.com

//如果URL = 192.168.8.1:80/index.html
console.log(window.location.host)
//  输出  192.168.8.1:80

//设置
window.location.host= "192.168.8.1";
// 设置后网页会进行跳转

0x03 URL 关联的端口号码

// 如果 URL 为 https://github.com/chenchenwuai?a=111&b=222
//获取
console.log(window.location.port)
//  输出空值  ""

//如果URL = 192.168.8.1:80/index.html
console.log(window.location.port)
//  输出  80

//设置
window.location.port= "81";
// 设置后网页会进行跳转

0x04 指定的文件名或路径

// 如果 URL 为 https://github.com/chenchenwuai?a=111&b=222
//获取
console.log(window.location.pathname)
//  输出  /chenchenwuai

//设置
window.location.pathname= "/abcde";
// 设置后网页会进行跳转

0x05 “#”后面的分段

// 如果 URL 为 https://github.com/chenchenwuai#target?a=111&b=222
//获取
console.log(window.location.hash)
//  输出  #target?a=111&b=222

//设置
window.location.hash= "#abcde";
// 设置后网页会变化

0x06 “?”后面的分段,请求参数

// 如果 URL 为 https://github.com/chenchenwuai?a=111&b=222
//获取
console.log(window.location.serach)
//  输出  ?a=111&b=222

//设置
window.location.serach= "?c=333";
// 设置后网页会进行跳转

0x... 

猜你喜欢

转载自blog.csdn.net/chenwuai/article/details/83176474
今日推荐