需求:獲取瀏覽器當前窗口的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;
}