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

2025-11-10 18:09:46 世界杯瑞典 487

需求:获取浏览器当前窗口的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;

}

万达财富的理财靠谱么?财富快车怎么样?
「霜降」節氣到!霜降牛命名由來曝光 主廚教分辨霜降牛、雪花牛