網址的拆解是前端常識,但網路上流傳的某些「取得 MAC 位址」寫法早已不能運作。以下把可用的與不可用的分清楚。
thisURL = document.URL;
thisHREF = document.location.href;
thisSLoc = self.location.href;
thisDLoc = document.location;
thisTLoc = top.location.href; // 最上層視窗
thisPLoc = parent.document.location; // 父視窗
thisTHost = top.location.hostname;
thisHost = location.hostname;
// 拆出檔名
tmpHPage = thisHREF.split("/");
thisHPage = tmpHPage[tmpHPage.length - 1];
tmpUPage = thisURL.split("/");
thisUPage = tmpUPage[tmpUPage.length - 1];
建議改用 URL 物件,各部位現成可用,不必自己切字串:
const u = new URL(location.href);
u.origin; u.pathname; u.search; u.hash;
網路上流傳的寫法大致如下:
<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>
<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 == true) {
if (objObject.IPEnabled && objObject.IPAddress(0) != null) {
sIPAddr = objObject.IPAddress(0);
}
if (objObject.MACAddress != null) sMacAddr = objObject.MACAddress;
if (objObject.DNSHostName != null) sDNSName = objObject.DNSHostName;
}
</script>
這段程式依賴三個早已消失或被封鎖的技術:
ActiveX 物件:classid 指向的是 Windows Script Host 的 WMI 元件。ActiveX 在 IE11 之後逐步停用,其他瀏覽器從未支援。
WMI 查詢:Win32_NetworkAdapterConfiguration 需要完整的系統權限,即便在 IE 上也早已被安全性原則封鎖。
HTML 標籤上的 FOR 與 EVENT 屬性:這是 IE 專屬的事件綁定語法,從未進入標準,其他瀏覽器一律忽略。
就算在當年,它也只讀得到「第一個啟用的網路介面」,多網卡、VPN、虛擬機器的情況下結果都不可靠。
這是設計上的決定,不是技術限制。瀏覽器若能任意讀取 MAC 位址,等於提供了一個無法更換的裝置指紋,廣告追蹤與跨站身分辨識會立刻氾濫。因此所有現代瀏覽器都不開放這個能力,也沒有替代 API。
至於 IP 位址,前端唯一能看到的是公開 IP,取得方式請由伺服器端回傳(例如讀取請求的 RemoteAddr),前端再用 fetch 取用;本機的內網 IP 一律讀不到。
請在伺服器端處理:以登入帳號作為識別依據,搭配 httpOnly 的 cookie 或 token 維持工作階段。若需要裝置管理或資產盤點這類資訊,那是本機應用程式(搭配原生外掛或 agent)的工作,不該由網頁負責。