hi,欢迎访问本站!
当前位置: 首页Web前端正文

js获取当前页面的url信息

墨初 Web前端 286阅读

js脚本代码可以通过使用 window.location 方法来获取或设置网址,也可以获取到当前网址中的各个参数,比如网址中的域名,网址中的端口以及网址中的参数等等。

window.location

window.location:此方法可以获取网页的网址,或将网址重定向新的网页也可以通过以下的属性获取网址的各个参数。

属性值

参数描述
pathname设置或获取对象指定的文件名或路径
href设置或获取整个 URL 为字符串
port设置或获取与 URL 关联的端口号码
protocol设置或获取 URL 的协议部分
host设置或获取 location 或 URL 的 hostname 和 port 号码
search设置或获取 href 属性中跟在问号后面的部分

window.location.pathname

设置或获取对象指定的文件名或路径。

例:

http://localhost:8086/topic/index?topicId=361
console.log(window.location.pathname);
// /topic/index

window.location.href

设置或获取整个 URL 为字符串。

例:

http://localhost:8086/topic/index?topicId=361
console.log(window.location.href);
http://localhost:8086/topic/index?topicId=361

window.location.port

设置或获取与 URL 关联的端口号码。

例:

http://localhost:8086/topic/index?topicId=361
console.log(window.location.port);
// 8086

window.location.protocol

设置或获取 URL 的协议部分。

例:

http://localhost:8086/topic/index?topicId=361
console.log(window.location.protocol);
// http:

window.location.host

设置或获取 location 或 URL 的 hostname 和 port 号码。

例:

http://localhost:8086/topic/index?topicId=361
console.log(window.location.host);
// http:localhost:8086

window.location.search

设置或获取 href 属性中跟在问号后面的部分。

例:

http://localhost:8086/topic/index?topicId=361
console.log(window.location.search);
// ?topicId=361
声明:无特别说明,转载请标明本文来源!
相关推荐