Java – Get Firefox Browser Version

The post shows you how to get the version of Firefox browser using Java.

To do this, we simply look at User-Agent data (request.getHeader("User-Agent")) to determine whether the visitors are using Firefox browser and then extract Firefox version from it.

 

1. Implementation

Browser.java
package com.bytenota;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;

public class Browser {
    
    public static String getFirefoxVersion(HttpServletRequest request) {
        String version = null;
        
        String userAgent = request.getHeader("User-Agent").toLowerCase();
        if (userAgent.contains("firefox")) {
            Pattern pattern = Pattern.compile("firefox\\/([0-9]+\\.*[0-9]*)");
            Matcher matcher = pattern.matcher(userAgent);
            if (matcher.find()) {
                version = matcher.group(1);
            }
        }
        
        return version;
    }
}

The above method returns the version if the browser is Firefox and we extract the version in the User-Agent successfully, null if the browser is not Firefox.


 

2. Usage and Example

Let’s create a jsp file in your web application with the following content.

index.jsp
<%@page import="com.bytenota.Browser"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Get Firefox browser version using Java</title>
    </head>
    <body>
        <%
            // assumming that the UserAgent is:
            // Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
            String firefoxVersion = Browser.getFirefoxVersion(request);
            out.write("The version of Firefox is " + firefoxVersion);
        %>
    </body>
</html>

Assuming that you have opened this jsp webpage in the Firefox browser. And the output you will get is:

The version of Firefox is 60.0