js 获取浏览器当前窗口url及参数等

需求:获取浏览器当前窗口的url及参数。

思路:通过window.location获取url的信息。

1.window.location的属性

/* 
href:完整的URL字符串。
protocol:URL的协议部分,如"http:"或"https:"。
host:主机名和端口号(如果指定了的话),如"example.com:8080"。
hostname:只是主机名部分,如"example.com"。
port:端口号(如果URL中包含的话),如"8080"。
pathname:URL的路径部分(URL中域名后的部分),如"/folder/page.html"。
search:URL的查询字符串部分,包括问号(?),如"?key1=value1&key2=value2"。
hash:URL的哈希值部分,包括井号(#),如"#section1"。
*/

// 获取完整的URL  
var url = window.location.href;  
console.log(url); // 输出: https://example.com:8080/folder/page.html?query=123#section1  
  
// 获取协议  
var protocol = window.location.protocol;  
console.log(protocol); // 输出: https:  
  
// 获取主机名(包含端口号,如果指定了的话)  
var host = window.location.host;  
console.log(host); // 输出: example.com:8080  
  
// 获取主机名(不包括端口号)  
var hostname = window.location.hostname;  
console.log(hostname); // 输出: example.com  
  
// 获取端口号  
var port = window.location.port;  
console.log(port); // 输出: 8080  
  
// 获取路径  
var pathname = window.location.pathname;  
console.log(pathname); // 输出: /folder/page.html  
  
// 获取查询字符串  
var search = window.location.search;  
console.log(search); // 输出: ?query=123  
  
// 获取哈希值  
var hash = window.location.hash;  
console.log(hash); // 输出: #section1

2.例如获取IP+端口

function getBaseUrl() {  
    const { protocol, hostname, port } = window.location;    
    const baseUrl = `${protocol}//${hostname}`;
    if (port && (protocol === 'http:' && port !== '80' || protocol === 'https:' && port !== '443')) {
              baseUrl += `:${port}`;
         }
    return baseUrl;  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值