I have an array of key:value pairs containing a keyword found in the useragent string. I need to loop through these pairs and match each value for match to the navigator.userAgent string. I know browser sniffing is frowned upon but it’s not up to me. Instead of Ext.each (which I’m not all that familiar with) I can use a for loop. Here is the jsfiddle for how I went about solving this problem the first time
http://jsfiddle.net/tagZN/83/ but I was told to do this other way instead.
<script type="text/javascript">
var deviceProfiles =
[
'{match:Macintosh, name:Mac Desktop}',
'{match:Windows NT, name:Windows Desktop}',
'{match:Ubuntu, name:Ubuntu,layout:desktop}',
'{match:Silk, name:Kindle Fire,layout:tablet}'
];
var ua = navigator.userAgent;
var re = new RegExp(deviceProfiles.join("|"), "i");
var identifyDevice = function( ua )
{
Ext.each(
deviceProfiles,
function( profile )
{
return ua.match( profile.match ) == nil;
}
);
}
</script>
I was also originally given deviceProfile as (and told to fill in values for match & name):
var deviceProfiles =
[
{
match: 'user agent regular expression here',
name: 'name of device here',
},
{
match: 'user agent regular expression here',
name: 'name of device here'
},
{
match: 'user agent regular expression here',
name: 'name of device here',
}
];
but it didn’t work so I changed it to what you saw above. Was this a bad call. I am trying to decipher what I was given. I also created
var re = new RegExp(deviceProfiles.join("|"), "i");
even though it’s not being used yet, I believe it will be necessary. I have tested this by setting ua equal to an actually user agent string that I copied and pasted where the keyword is contained in the array deviceProfiles and still no luck.
Any help is truly appreciated.
You are correct that browser sniffing is a flawed strategy for anything other than casual amusement.
There are a number of issues with your code, not the least being that deviceProfiles is an array of strings, not objects. Also, the code is attempting to detect the user agent and then making a guess about the platform. It really has nothing to do with the device e.g. running IE in a virtual machine on a non-windows laptop returns “Windows desktop”, which is completely wrong. And what should be done with user agent strings that aren’t matched?
There are thousands of browsers on devices like phones, laptops, game consoles and TVs. More devices access the internet and web pages every day, can you sniff all of them?
Anyhow, here’s how to do what you are trying to do: