需求:獲取瀏覽器當(dāng)前窗口的url及參數(shù)屎暇。
思路:通過window.location獲取url的信息。
1.window.location的屬性
/*
href:完整的URL字符串锅必。
protocol:URL的協(xié)議部分,如"http:"或"https:"慧脱。
host:主機(jī)名和端口號(hào)(如果指定了的話)酬滤,如"example.com:8080"。
hostname:只是主機(jī)名部分弄诲,如"example.com"愚战。
port:端口號(hào)(如果URL中包含的話),如"8080"。
pathname:URL的路徑部分(URL中域名后的部分)寂玲,如"/folder/page.html"塔插。
search:URL的查詢字符串部分,包括問號(hào)(?)敢茁,如"?key1=value1&key2=value2"佑淀。
hash:URL的哈希值部分,包括井號(hào)(#)彰檬,如"#section1"伸刃。
*/
// 獲取完整的URL
var url = window.location.href;
console.log(url); // 輸出: https://example.com:8080/folder/page.html?query=123#section1
// 獲取協(xié)議
var protocol = window.location.protocol;
console.log(protocol); // 輸出: https:
// 獲取主機(jī)名(包含端口號(hào),如果指定了的話)
var host = window.location.host;
console.log(host); // 輸出: example.com:8080
// 獲取主機(jī)名(不包括端口號(hào))
var hostname = window.location.hostname;
console.log(hostname); // 輸出: example.com
// 獲取端口號(hào)
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;
}