browscap.ini
that get_browser()
depends on is found at http://browsers.garykeith.com/downloads
Does anyone know how to port the seemingly simple get_browser()
to CFML?
Thanks!
browscap.ini
that get_browser()
depends on is found at http://browsers.garykeith.com/downloads
Does anyone know how to port the seemingly simple get_browser()
to CFML?
Thanks!
Solved!
This is based on http://forums.adobe.com/thread/620512, and optimized for performance with improved correctness.
It is still quite slow (~1s) because working with ini file with ColdFusion means every getProfileString()
is a disk I/O! Might be faster with SSD. :)
function get_browser(user_agent=CGI.HTTP_USER_AGENT, browscap_ini=expandPath("./browscap.ini"))
{
var result = {};
// Read wildcard patterns from the INI file
var browscap_list = getProfileSections(browscap_ini);
// Seed some variables
var browser_champion_pattern = "*";
// Loop through the patterns to find the best match (relative to length of name pattern)
for (var browser_name_pattern in browscap_list)
{
if (len(browser_name_pattern) >= len(browser_champion_pattern))
{
// Massage the wildcard into useable regex
var browser_name_regex = replaceList(browser_name_pattern, ".,*,?,(,),[,]", "\.,.*,.,\(,\),\[,\]");
if (left(browser_name_pattern, 1) != "*")
browser_name_regex = "^" & browser_name_regex;
if (right(browser_name_pattern, 1) != "*")
browser_name_regex &= "$";
// Test the resulting regex against the user agent
if (reFindNoCase(browser_name_regex, user_agent))
browser_champion_pattern = browser_name_pattern;
}
}
// Set the winning regex patterns
var browser_name_pattern = browser_champion_pattern;
// Fetch the winning info
var keynames = listToArray(browscap_list[browser_champion_pattern]);
for (var keyname in keynames)
result[keyname] = getProfileString(browscap_ini, browser_champion_pattern, keyname);
// Fetch the rest of the info from parents
while (structKeyExists(result, "parent"))
{
var parent = result.parent;
structDelete(result, "parent");
var keynames = listToArray(browscap_list[parent]);
for (var keyname in keynames)
if (!structKeyExists(result, keyname))
result[keyname] = getProfileString(browscap_ini, parent, keyname);
}
return result;
}