SWFObject 2.2 currently uses an IE detection technique proposed by Andrea Giammarchi in 2009:
var isIE = !+"v1";
It’s a hack that relied on Internet Explorer’s unique handling of vertical spaces (v). Now that it has stopped working, I decided to take a quick look at what others are doing.
Code language: PHP (php)
var isIE = /*@cc_on!@*/!1;
One way to get around the compressor issue (as pointed out by a commenter on Dean Edwards’ post) is to wrap the conditional compilation statement in an
var isIE = eval("/*@cc_on!@*/!1");
eval() is evil, I won’t use this approach.
One of the most long-standing methods of detecting Internet Explorer is to examine the userAgent string:
var isIE = /msie/gi.test(navigator.userAgent);
However, this isn’t foolproof, as most browsers allow you to change the userAgent string at will. For example, I changed Safari’s userAgent string to report itself as Internet Explorer 8, and
So far, the only test I’ve found that seems to fit the bill is the old
var isIE = navigator.appName === 'Microsoft Internet Explorer';
Is it perfect? Not a chance, but it has a lot of upside: it works in IE9, doesn’t get damaged when compressed, doesn’t rely on any hacky tricks (as fun as they might be), and isn’t affected by spoofed userAgent strings.
What are the Frameworks using?
jQuery uses userAgent sniffing, and includes a warning that it’s unreliable. MooTools uses a combination of properties from the
navigator object, including
navigator.platform. It’s interesting to note that MooTools previously used feature detection to infer the browser brand, but changes introduced by Firefox 3.6 prompted the MooTools team to switch to a userAgent-based detection method instead. (Nicholas Zakas wrote an interesting blog post about MooTools’ prior detection technique.)
Dustin Diaz’s Bowser detection script uses userAgent exclusively.
Why sniff in the first place?
Before you get down on me for even talking about sniffing, relax, I agree with you. I much prefer feature detection to browser sniffing; this is especially important with our quickly changing browser landscape: HTML5, web storage, geolocation, etc. (Modernizr is a great tool for modern feature detection.)
So we carry on. I use feature detection for just about everything, but once in a while I need a global “are you Internet Explorer?”, and browser sniffing fits the bill.