以下屬性均屬於 window.location 或 document,可直接在控制台輸出觀察:
var thisURL = document.URL;
var thisHREF = document.location.href;
var thisSLoc = self.location.href;
var thisDLoc = document.location;
var thisTLoc = top.location.href; // 頂層窗口完整 URL
var thisPLoc = parent.document.location; // 父窗口 Location 物件
var thisTHost = top.location.hostname; // 頂層窗口域名
var thisHost = location.hostname; // 當前窗口域名
// 獲取當前頁面文件名
var tmpHPage = thisHREF.split("/");
var thisHPage = tmpHPage[tmpHPage.length - 1];
var tmpUPage = thisURL.split("/");
var thisUPage = tmpUPage[tmpUPage.length - 1];
| 屬性 | 說明 | 範例 |
|---|---|---|
href | 完整 URL | https://example.com:8080/path/page.html?query=1#hash |
protocol | 協議(含冒號) | https: |
host | 域名+端口 | example.com:8080 |
hostname | 域名 | example.com |
port | 端口號 | 8080 |
pathname | 路徑(含前導 /) | /path/page.html |
search | 查詢字符串(含 ?) | ?query=1 |
hash | 錨點(含 #) | #section1 |
origin | 協議+域名+端口(只讀) | https://example.com:8080 |
⚠️ 重要提示:以下代碼依賴 ActiveXObject 及 WMI(Win32_NetworkAdapterConfiguration),僅在 IE 瀏覽器中運行,且需用戶授權「初始化並腳本運行未標記為安全的 ActiveX 控件」。現代瀏覽器(Chrome、Firefox、Edge)完全不支援,純前端無法獲取用戶真實 IP/MAC,請勿在生產環境依賴此方案。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
</head>
<body>
<object classid="CLSID:76A64158-CB41-11D1-8B02-00600806D9B6" id="locator" style="display:none"></object>
<object classid="CLSID:75718C9A-F029-11d1-A1AC-00C04FB6C223" id="foo" style="display:none"></object>
<form name="myForm">
MAC地址:<input type="text" name="macAddress"><br/>
IP地址:<input type="text" name="ipAddress"><br/>
主機名:<input type="text" name="hostName">
</form>
<script language="javascript">
var sMacAddr = "", sIPAddr = "", sDNSName = "";
var service = locator.ConnectServer();
service.Security_.ImpersonationLevel = 3;
service.InstancesOfAsync(foo, 'Win32_NetworkAdapterConfiguration');
</script>
<script FOR="foo" EVENT="OnObjectReady(objObject,objAsyncContext)" LANGUAGE="JScript">
if (objObject.IPEnabled != null && objObject.IPEnabled != "undefined" && objObject.IPEnabled == true) {
if (objObject.IPEnabled && objObject.IPAddress(0) != null && objObject.IPAddress(0) != "undefined")
sIPAddr = objObject.IPAddress(0);
if (objObject.MACAddress != null && objObject.MACAddress != "undefined")
sMacAddr = objObject.MACAddress;
if (objObject.DNSHostName != null && objObject.DNSHostName != "undefined")
sDNSName = objObject.DNSHostName;
}
</script>
<script FOR="foo" EVENT="OnCompleted(hResult,pErrorObject, pAsyncContext)" LANGUAGE="JScript">
myForm.macAddress.value = sMacAddr;
myForm.ipAddress.value = sIPAddr;
myForm.hostName.value = sDNSName;
</script>
</body>
</html>
https://api.ipify.org?format=json)或自建後端接口返回 req.ip。os.hostname())。URL 解析請使用標準 location 物件或 URL/URLSearchParams API;客戶端網絡信息(IP/MAC/主機名)在現代瀏覽器中無法通過純前端獲取,請轉向後端接口或第三方服務。