有没有一种方法可以将用户的默认浏览器作为字符串返回?什么我寻找方法返回默认浏览器作为一个字符串?
例子:
System.out.println(getDefaultBrowser()); // prints "Chrome"
有没有一种方法可以将用户的默认浏览器作为字符串返回?什么我寻找方法返回默认浏览器作为一个字符串?
例子:
System.out.println(getDefaultBrowser()); // prints "Chrome"
您可以通过使用登记[1]和正则表达式来提取默认浏览器作为字符串完成这个方法。我不知道这样做的“干净”方式。
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";
}
现在每当调用getDefaultBrowser()
时,都应返回Windows的默认浏览器。
测试的浏览器:
正则表达式的说明(/(?=[^/]*$)(.+?)[.]
):
/(?=[^/]*$)
匹配上次弦[.]
中出现/
匹配文件扩展名(.+?)
的.
捕获这两个匹配的字符之间的字符串。你可以看到这是如何看的registry
权之前,我们测试对正则表达式的值来捕获(我加粗的是什么捕获):
(默认)REG_SZ“ C:/程序文件(x86)/ Mozilla Firefox浏览器/ 火狐的.exe” -osint -url “%1”
[1]仅限Windows。我无法访问Mac或Linux计算机,但通过浏览互联网,我认为com.apple.LaunchServices.plist
将默认浏览器值存储在Mac上,而在Linux上,我认为您可以执行命令xdg-settings get default-web-browser
以获取默认浏览器。虽然我可能会错,但也许有人可以访问这些人愿意为我测试并评论如何实施它们?
_当将Internet Explorer设置为默认浏览器时,“HKEY_CLASSES_ROOT \ http \ shell \ open \ command”_不会更新。至少不是在我的电脑上,Windows 7. – 2013-07-11 13:52:19
@StevenJeuris奇怪的是,我运行的是相同的操作系统,并且在设置IE时更新了注册表。 – syb0rg 2013-07-11 13:58:50
为我更新了以下注册表值:_“HKEY_CURRENT_USER \ Software \ Microsoft \ Windows \ Shell \ Associations \ UrlAssociations \ http \ UserChoice”_。但是,它存储ProgID而不是路径。 – 2013-07-11 14:01:07
为什么你需要用户默认浏览器?我猜你的代码将运行在服务器端而不是客户端,或者你正在制作桌面应用程序? – 2013-05-30 11:16:16
需要查找用户的默认浏览器有很多原因,我使用它的是我的客户的统计数据。这个函数会告诉我他们使用了哪些浏览器,如果他们安装了某个浏览器,我可能会推荐使用不同的软件。 – syb0rg 2013-05-30 14:05:49
为什么你需要默认浏览器?你可以做String userAgent = request.getHeader(“User-Agent”);然后从中获取浏览器。大多数人将IE作为默认浏览器,并将使用Chrome或Firefox。 – 2013-05-30 14:44:56