有沒有一種方法可以將用戶的默認瀏覽器作爲字符串返回?什麼我尋找方法返回默認瀏覽器作爲一個字符串?
例子:
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