views:

566

answers:

8
If browser == IE6{
alert('hi');
}
+3  A: 
  var ua = window.navigator.userAgent;
  var msie = ua.indexOf ( "MSIE " );

  if ( msie > 0 )      // If Internet Explorer, return version number
     return parseInt (ua.substring (msie+5, ua.indexOf (".", msie )));
  else                 // If another browser, return 0
     return 0;

Source : http://support.microsoft.com/kb/167820

Yassir
-1: Never use user-agent to identify a browser. Use feature-based detection instead.
Andrew Moore
Why what is the reason ? it woks fine on IE, FF and chrome !
Yassir
@Yassir: The are a lot of browsers out there using the same engine (Trident 4) as MSIE 6. Using feature detection versus user agent detection catches those. It also has less false positives than user agent detection (a lot of browser have an option to change their UA to pass as another browser).
Andrew Moore
Why are you downvoting this answer? Yes, feature detection is ok but he's answering the OP's question properly.Pretty sure the OP didn't ask for anal evangelism about how feature detection > browser detection in some circumstances.
Will Morgan
Finally an answer to the actual question asked. However, it's not very concise. A regular expression is going to be much nicer.
thomasrutter
@Andrew, nobody asked about how to detect browsers which are not IE6 but which do use Trident. The question is *specifically* about IE6
kibibu
+13  A: 

Conditional comments are a good alternative:

<!--[if IE 6]>
var everythingIsBroken = true;
<![endif]-->
apphacker
Is this a serious answer?
TIMEX
Should be. Conditional comments are something introduced by Microsoft as a way to only run certain code in (specific versions of) IE. Because they are in HTML comments, other browsers will ignore it.
Aistina
Conditional comments are not a viable alternative. While they work in IE directly, they can be disabled in other similar browser when using the WebBrowser Control. In which case your conditional comment becomes useless. Most third-party browser using the Trident4 engine have conditional comments turned off.
Andrew Moore
And what other browsers are that? If you're going to support third party browsers using Trident4 you're going to have more issues than just conditional comments not working...you might as well support W3.org's Amaya. Ignore Andrew's comment, conditional comments always work for "down-level" browsers.
apphacker
Also conditional comments are Microsoft's recommended way of targeting IE6.
apphacker
@apphacker: Internet Explorer 6 uses the Trident 4 engine, but I guess that's beside the point...
Andrew Moore
I know that, I was talking about *third party* browsers using Trident4...especially ones with various options disabled.
apphacker
Downvoted simply because the original question contains the term "using Javascript". HTML conditional comments are not a Javascript solution. And when you're writing portable Javascript, like a Javascript library, you need a Javascript solution.
thomasrutter
+5  A: 

Don't base your detection on the user-agent. There are plenty of other browsers out there that use the Trident 4 engine (the one IE6 use) that are not IE6.

The answer is simple: don't detect the browser, detect the engine. To do that, you must use what's called feature based detection.


Using feature based detection has the following advantages:

  • Detects all browsers using similar rendering engine than target.
  • Easier code branching to work around issues of a rendering engine.
  • Less false positives (UAs can be modified to pass as another browser, features can't).

The following script uses browser features to detect the engine. Credit to The MooTools production team (http://mootools.net/developers/).

Note: The snippet below has been modified to work without the MooTools javascript framework. If you do wish to work with MooTools, you no longer need this code, it is part of the distribution.

function $tryCatch(){
    for (var i = 0, l = arguments.length; i < l; i++){
        try {
            return arguments[i]();
        } catch(e){}
    }
    return null;
};

var Browser = {

    Engine: {name: 'unknown', version: 0},

    Platform: {name: (window.orientation != undefined) ? 'ipod' : (navigator.platform.match(/mac|win|linux/i) || ['other'])[0].toLowerCase()},

    Features: {xpath: !!(document.evaluate), air: !!(window.runtime), query: !!(document.querySelector)},

    Plugins: {},

    Engines: {

        presto: function(){
            return (!window.opera) ? false : ((arguments.callee.caller) ? 960 : ((document.getElementsByClassName) ? 950 : 925));
        },

        trident: function(){
            return (!window.ActiveXObject) ? false : ((window.XMLHttpRequest) ? ((document.querySelectorAll) ? 6 : 5) : 4);
        },

        webkit: function(){
            return (navigator.taintEnabled) ? false : ((Browser.Features.xpath) ? ((Browser.Features.query) ? 525 : 420) : 419);
        },

        gecko: function(){
            return (!document.getBoxObjectFor && window.mozInnerScreenX == null) ? false : ((document.getElementsByClassName) ? 19 : 18);
        }

    }

};

Browser.Platform[Browser.Platform.name] = true;

Browser.detect = function(){

    for (var engine in this.Engines){
        var version = this.Engines[engine]();
        if (version){
            this.Engine = {name: engine, version: version};
            this.Engine[engine] = this.Engine[engine + version] = true;
            break;
        }
    }

    return {name: engine, version: version};

};

Browser.detect();

Browser.Request = function(){
    return $tryCatch(function(){
        return new XMLHttpRequest();
    }, function(){
        return new ActiveXObject('MSXML2.XMLHTTP');
    }, function(){
        return new ActiveXObject('Microsoft.XMLHTTP');
    });
};

Browser.Features.xhr = !!(Browser.Request());

Browser.Plugins.Flash = (function(){
    var version = ($tryCatch(function(){
        return navigator.plugins['Shockwave Flash'].description;
    }, function(){
        return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
    }) || '0 r0').match(/\d+/g);
    return {version: parseInt(version[0] || 0 + '.' + version[1], 10) || 0, build: parseInt(version[2], 10) || 0};
})();

function $exec(text){
    if (!text) return text;
    if (window.execScript){
        window.execScript(text);
    } else {
        var script = document.createElement('script');
        script.setAttribute('type', 'text/javascript');
        script[(Browser.Engine.webkit && Browser.Engine.version < 420) ? 'innerText' : 'text'] = text;
        document.head.appendChild(script);
        document.head.removeChild(script);
    }
    return text;
};

Just include this JavaScript class and you can detect IE6 and any other browser using the Trident4 engine by doing the following:

if(Browser.Engine.trident4) {
   alert('IE6 or similar...');
} elseif(Browser.Engine.name == "trident") {
   alert('Internet Explorer Trident Rendering Engine Version ' + Browser.Engine.version);
}
Andrew Moore
This doesn't seem like the feature detection you're recommending in your comments to other answers to this question.
Tim Down
@Tim Down: I said feature **-based** detection, not feature detection. Feature-based detection tried to identify an **engine** based on features implemented in the JavaScript engine of that particular rendering engine. Feature detection allows you to turn on or off features based on if it was detected as supported. Knowing the engine used to render the page allows you to fix quirks with the rendering of dynamic elements on that page. This method is also called object-based detection.
Andrew Moore
This is feature inference, and flaky. What inferences would/should you make based on the existence of `document.getBoxObjectFor` or `window.mozInnerScreenX` or `navigator.taintEnabled`? If you're going to use these to vary behaviour that is unrelated to these objects being tested, it's only a small step up from examining the userAgent string to me. These objects may be overridden by JavaScript and are generally non-standard and therefore subject to the whims of browser manaufacturers: MooTools was stung by this quite recently (http://ajaxian.com/archives/mootools-call-to-upgrade).
Tim Down
Not wanting to single out this answer, but in general, I am so tired of seeing answers to questions on Stackoverflow that basically say "don't do that". Can't we just trust that the question asker has a good reason to specifically detect IE6, rather than do feature-based detection? For example, maybe the question asker wants to implement a warning to users saying "your version of Internet Explorer is out of date".
thomasrutter
+1  A: 

What is the best way to detect <browser_x> using JavaScript?

By not.

As Andrew Moore has mentioned in comments in this post, you should be using feature detection. This will make your code more "future-proof". If another browser includes, or no longer supports a feature in the future, then your code will be safe. There are a number of sites out there explaining how to handle this. The concept is huge and covers a lot of concepts, so rather than writing an essay/book on this, here are some resources to use:

Dan Herbert
A: 
if(!window.addEventListener && !window.XMLHttpRequest && window.attachEvent){
// It quacks like IE-6, but it could be 5.5.
}
kennebec
A: 

I'm not sure if there's a special reason why you want to detect IE 6 but in general it is better to try to detect the browser's features rather than detecting the browser. You can do this easily with JQuery using jQuery.support: http://api.jquery.com/jQuery.support/.

jcmoney
Is it really a good idea to recommend someone use a massive JavaScript library or framework for a simple problem that requires nothing of the kind for the solution?
apphacker
I wouldn't call jQuery "massive." What the poster is asking how to do is something that pretty much shouldn't be done so a more valuable piece of advice is why that is and what he/she should be doing instead so that he/she follows good programming practice.
jcmoney
+1  A: 

At the risk of actually answering the question that was asked (and assuming for a moment the asker has a good reason to specifically detect IE6):

if (/\bMSIE 6/.test(navigator.userAgent) && !window.opera) {
  // yep, browser claims to be IE6
}
thomasrutter
A: 

Very late addition.

In addition to the HTML conditional comments used in apphacker's answer, microsoft's JScript implementation also provides conditional comments for javascript:

<script type="text/javascript">
    var isIE6 = /*@cc_on/*@if(@_jscript_version<=5.6)1@else@*/0/*@end@*/;

    if (isIE6) {
        alert("You're screwed");
    }
</script>

The good thing is that it can also be used in external .js files.

For a table listing the version of JScript that are implemented by Microsoft host applications: http://msdn.microsoft.com/en-us/library/s4esdbwz%28VS.85%29.aspx

Jacco