Method returning default browser as a String?

我的梦境 提交于 2019-11-28 23:18:49

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!