萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 判斷用戶端作業系統與瀏覽器:GetOs 函數解析 User-Agent 字串

ASP 解析 User-Agent 識別客戶端 OS 與瀏覽器

透過 Request.ServerVariables("HTTP_USER_AGENT") 取得 UA 字串,本函數 GetOs(content, type) 支援兩種模式:type=0 解析作業系統,type=1 解析瀏覽器版本。涵蓋 Windows 9x 到 Vista、Unix/Linux/Mac 等主流平台。

完整函數代碼

Function GetOs(content, systemOrBrowser)
    Dim temp
    temp = Split(content, ";")
    Select Case systemOrBrowser
        Case 0 ' 作業系統
            If InStr(content, "Windows NT 6.0") Then GetOs = "Windows Vista"
            ElseIf InStr(content, "Windows NT 5.2") Then GetOs = "Windows 2003"
            ElseIf InStr(content, "Windows NT 5.1") Then GetOs = "Windows XP"
            ElseIf InStr(content, "Windows NT 5.0") Then GetOs = "Windows 2000"
            ElseIf InStr(content, "Windows NT") Then GetOs = "Windows NT"
            ElseIf InStr(content, "Windows 9") Then GetOs = "Windows 9x"
            ElseIf InStr(content, "unix") Then GetOs = "Unix"
            ElseIf InStr(content, "linux") Then GetOs = "Linux"
            ElseIf InStr(content, "SunOS") Then GetOs = "SunOS"
            ElseIf InStr(content, "BSD") Then GetOs = "BSD"
            ElseIf InStr(content, "Mac") Then GetOs = "Mac"
            Else GetOs = "Other"
            End If
        Case 1 ' 瀏覽器
            If InStr(content, "Opera") Then
                GetOs = Replace(Left(content, InStr(content, "(") - 1), "/", " ")
            ElseIf InStr(content, "MSIE") > 0 Then
                GetOs = Trim(temp(1)) ' 通常第 2 段為版本
            Else
                ' Firefox/Chrome/Safari 等
                GetOs = Replace(Right(temp(4), Len(temp(4)) - InStrRev(temp(4), " ")), "/", " ")
            End If
    End Select
End Function

呼叫範例

Dim ua, osName, browserName
ua = Request.ServerVariables("HTTP_USER_AGENT")
osName = GetOs(ua, 0)
browserName = GetOs(ua, 1)
Response.Write "OS: " & osName & "
Browser: " & browserName

User-Agent 字串範例

  • IE 6 on XP: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)
  • Chrome on Win10: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36
  • iPhone Safari: Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1

現代化建議

UA 字串極易偽造且格式多變,建議:

  1. 改用成熟函式庫 (如 UAParser.js 移植版或伺服器端 user-agent-parser NuGet 套件)。
  2. 僅作統計分析用途,勿作為核心業務邏輯判斷依據 (如強制導向特定頁面)。
  3. 回應式設計 (RWD) 配合 CSS Media Query 取代瀏覽器偵測。
copyright © 萬盛學電腦網 all rights reserved