18

Is there a method that will return a user's default browser as a String?

Example of what I am looking for:

System.out.println(getDefaultBrowser()); // prints "Chrome"
syb0rg
  • 8,057
  • 9
  • 41
  • 81
  • Why do you need users default browser?I am guessing your code will run on server side rather than client side or you are making a desktop app? – Aniket Thakur May 30 '13 at 11:16
  • There are plenty of reasons for needing to find a user's default browser, the one I'm using it for is statistical data with my clients. This function will tell me what browsers they use, and perhaps I will have my code recommend different software if they have a certain browser installed. – syb0rg May 30 '13 at 14:05
  • Why do you need default browser for that? You can do String userAgent = request.getHeader("User-Agent"); and then get browser from it. Most people will have IE as default browser and will be using Chrome or Firefox. – Aniket Thakur May 30 '13 at 14:44
  • 2
    I'm not sure you know what you are talking about anymore. If they are using Chrome or Firefox, then they have probably set that as their default browser. Also, you don't consider offline use with your suggestion at all, and you always have to consider all the different scenarios of use when you implement code. My answer does consider offline use, since you can't always count on the client being connected to the internet. – syb0rg May 30 '13 at 18:23

1 Answers1

21

You can accomplish this method by using registries[1] and regular expressions to extract the default browser as a string. There isn't a "cleaner" way to do this that I know of.

public static String getDefaultBrowser()
{
    try
    {
        // Get registry where we find the default browser
        Process process = Runtime.getRuntime().exec("REG QUERY HKEY_CLASSES_ROOT\\http\\shell\\open\\command");
        Scanner kb = new Scanner(process.getInputStream());
        while (kb.hasNextLine())
        {
            // Get output from the terminal, and replace all '\' with '/' (makes regex a bit more manageable)
            String registry = (kb.nextLine()).replaceAll("\\\\", "/").trim();

            // Extract the default browser
            Matcher matcher = Pattern.compile("/(?=[^/]*$)(.+?)[.]").matcher(registry);
            if (matcher.find())
            {
                // Scanner is no longer needed if match is found, so close it
                kb.close();
                String defaultBrowser = matcher.group(1);

                // Capitalize first letter and return String
                defaultBrowser = defaultBrowser.substring(0, 1).toUpperCase() + defaultBrowser.substring(1, defaultBrowser.length());
                return defaultBrowser;
            }
        }
        // Match wasn't found, still need to close Scanner
        kb.close();
    } catch (Exception e)
    {
        e.printStackTrace();
    }
    // Have to return something if everything fails
    return "Error: Unable to get default browser";
}

Now whenever getDefaultBrowser() is called, the default browser for Windows should be returned.

Tested browsers:

  • Google Chrome (function returns "Chrome")
  • Mozilla Firefox (function returns "Firefox")
  • Opera (function returns "Opera")

Explanation of the regex (/(?=[^/]*$)(.+?)[.]):

  • /(?=[^/]*$) matches the last occurring / in the string
  • [.] matches the . in the file extension
  • (.+?) captures the string between those two matched characters.

You can see how this is captured by looking at the value of registry right before we test it against the regex (I've bolded what is being captured):

(Default) REG_SZ "C:/Program Files (x86)/Mozilla Firefox/firefox.exe" -osint -url "%1"


[1] Windows only. I don't have access to a Mac or Linux computer, but from looking around the Internet, I think com.apple.LaunchServices.plist stores the default browser value on a Mac, and on Linux I think you can execute the command xdg-settings get default-web-browser to get the default browser. I could be wrong on that though, maybe someone with access to those would be willing to test for me and comment on how to implement them?

syb0rg
  • 8,057
  • 9
  • 41
  • 81
  • 3
    _"HKEY_CLASSES_ROOT\http\shell\open\command"_ isn't updated when Internet Explorer is set as the default browser. At least not on my PC, Windows 7. – Steven Jeuris Jul 11 '13 at 13:52
  • @StevenJeuris Odd, I am running the same OS and that registry is updated when IE is set. – syb0rg Jul 11 '13 at 13:58
  • The follwing registry value is updated for me: _"HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice"_. However, it stores a ProgID and not a path. – Steven Jeuris Jul 11 '13 at 14:01
  • The funniest thing just happened to me. I copy pasted the above path from my own comment while writing the code to open the key, and it did not work. StackOverflow introduces the characters 0x200c and 0x200b to force the entire path to be split across two lines. So when you copy paste this to your source code, watch out! – Steven Jeuris Jul 11 '13 at 16:32
  • 1
    [Here is my working C# implementation](http://stackoverflow.com/a/17599201/590790) using the more recent key which seemingly should be used starting from Windows Vista. – Steven Jeuris Jul 11 '13 at 16:57