使用javascript确定操作系统

问题描述 投票:-1回答:2

我正在寻找一种获取客户端操作系统的Javascript通用方法。许多记录在案的解决方案都使用用户代理,而我在堆栈溢出时也遇到过时的类似问题/解答。下面提供了一个示例函数,但我想知道是否有更全面的版本可以满足以下准则:

  • 例如,所有现代且广泛使用的OS应该具有一个版本,而不是仅具有[[Windows 10,具有Windows 10Windows 7
  • 较旧且大部分冗余的OS可以组合在一起,例如
  • Windows 98
  • Windows Vista可能仅显示为[[Windows移动操作系统也应尽可能包含在版本中,例如Android 7.0
  • 代码不应太长,目的是要区分当前最流行的系统。
下面的示例放在一起时没有过多考虑,我正在寻找更好的版本
  • function getOS() { var osStr; var ua = navigator.userAgent.toLowerCase(); if (ua.indexOf("windows xp") !== -1) { osStr = "WindowsXP"; } else if (ua.indexOf("windows nt 6.1") !== -1) { osStr = "Windows7"; } else if (ua.indexOf("windows nt 10.0") !== -1) { osStr = "Windows10"; } else if (ua.indexOf("iemobile") !== -1 || ua.indexOf("windows phone") !== -1) { osStr = "WindowsMobile"; } else if (ua.indexOf("windows") !== -1) { osStr = "Windows"; } else if (ua.indexOf("ipad") !== -1) { osStr = "ipad"; } else if (ua.indexOf("ipod") !== -1) { osStr = "iTouch)"; } else if (ua.indexOf("iphone") !== -1) { osStr = "iPhone)"; } else if (ua.indexOf("cros") !== -1) { osStr = "ChromeOS"; } else if (ua.indexOf("android") !== -1) { osStr = "Android"; } else if (ua.indexOf("blackberry") !== -1) { osStr = "Blackberry"; } else if (ua.indexOf("palm") !== -1) { osStr = "PalmOS"; } else if (ua.indexOf("kindle") !== -1) { osStr = "Kindle"; } else if (ua.indexOf("ubuntu") !== -1) { osStr = "Ubuntu"; } else if (ua.indexOf("linux") !== -1) { osStr = "Linux"; } else if (ua.indexOf("nix") !== -1) { osStr = "UNIX"; } else { osStr = "Unknown"; } return osStr; }
  • javascript user-agent
    2个回答
    1
    投票
    对它们全部进行筛选是不切实际的。根据您的用例,将您所关心的内容过滤掉会更有利。

    但是,您可以使用一些API,这些API已经为您完成了艰苦的工作https://developers.whatismybrowser.com/api/features/user-agent-parse是一个很棒的工具,它将为您解析用户代理字符串

    这里是更全面的列表,其中包含每个示例https://www.whatsmyua.info/


    0
    投票
    function getPlatform() { var uap = UAParser(navigator.userAgent); var osVersion = uap.os.version; if (osVersion == null) { osVersion = ""; } var browserVersion = uap.browser.major; if (browserVersion == null) { browserVersion = ""; } var platform = uap.os.name + osVersion + "_" + uap.browser.name + browserVersion; platform = platform.replace(/\s/g, ''); return platform; }

    被调用时返回无空格字符串

    OS_UA,该字符串作为URL的一部分从客户端转发到服务器。
    © www.soinside.com 2019 - 2024. All rights reserved.