How can you detect the version of a browser?

后端 未结 28 2625
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 23:35

I\'ve been searching around for code that would let me detect if the user visiting the website has Firefox 3 or 4. All I have found is code to detect the type of browser but

28条回答
  •  耶瑟儿~
    2020-11-22 00:20

    Here is the java version for somemone who whould like to do it on server side using the String returned by HttpServletRequest.getHeader("User-Agent");

    It is working on the 70 different browser configuration I used for testing.

    public static String decodeBrowser(String userAgent) {
        userAgent= userAgent.toLowerCase();
        String name = "unknown";
        String version = "0.0";
        Matcher userAgentMatcher = USER_AGENT_MATCHING_PATTERN.matcher(userAgent);
        if (userAgentMatcher.find()) {
          name = userAgentMatcher.group(1);
          version = userAgentMatcher.group(2);
          if ("trident".equals(name)) {
            name = "msie";
            Matcher tridentVersionMatcher = TRIDENT_MATCHING_PATTERN.matcher(userAgent);
            if (tridentVersionMatcher.find()) {
              version = tridentVersionMatcher.group(1);
            }
          }
        }
        return name + " " + version;
      }
    
      private static final Pattern USER_AGENT_MATCHING_PATTERN=Pattern.compile("(opera|chrome|safari|firefox|msie|trident(?=\\/))\\/?\\s*([\\d\\.]+)");
      private static final Pattern TRIDENT_MATCHING_PATTERN=Pattern.compile("\\brv[ :]+(\\d+(\\.\\d+)?)");
    

提交回复
热议问题