user401231
user401231

Reputation:

Detect whether browser is IE 7 or lower?

So i am going to add a redirect to my site to toss every one that is using ie 7 or lower off to a different page and came up with this JavaScript, but it seems to have stopped working.

<script type="text/javascript">
 if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
  var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
   if (ieversion<=8)
    window.location = "ie.html" 
   }
   window.location = "main.html"
</script>

Upvotes: 14

Views: 15890

Answers (6)

Technotronic
Technotronic

Reputation: 8943

You can test it with this regular expression: (MSIE\ [0-7]\.\d+)

Here is a JavaScript example on how to use it:

if (/(MSIE\ [0-7]\.\d+)/.test(navigator.userAgent)) {
    // do something
}

Upvotes: 2

Tim Down
Tim Down

Reputation: 324477

Conditional comments (as suggested by @Kon) are the way to go. Here's a working implementation:

<script type="text/javascript">
    var ie7OrLower = false;
</script>

<!--[if lte IE 7]><script type="text/javascript">
   ie7OrLower = true;
</script><![endif]-->

<script type="text/javascript">
    window.location = ie7OrLower ? "ie.html" : "main.html";
</script>

Upvotes: 3

Kon
Kon

Reputation: 27431

Check out conditional comments.

So you can do something like:

<script type="text/javascript">
    <!--[if (!IE)|(gt IE 7)]>
      window.location = "ie.html" 
    <![endif]-->

    <!--[if lt IE 8]>
      window.location = "main.html"
    <![endif]-->
</script>

Upvotes: 9

DGM
DGM

Reputation: 26979

I'd just use the examples at http://www.ie6nomore.com/

Upvotes: 0

p.campbell
p.campbell

Reputation: 100557

Your code is always resulting to having gone to main.html. Even when the code falls into <8, you'll fall out of the if into setting to main.

Consider refactoring by either:

  • setting a return after setting to ie.

or

var redir="main.html";
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
{ 
   var ieversion=new Number(RegExp.$1);
   if (ieversion<=8)
   {
      redir = "ie.html";
   }
}
window.location = redir;

Upvotes: 11

James Hill
James Hill

Reputation: 61793

I've always used Quirks Mode's BrowserDetect.js for my browser detection needs. Check it out - http://www.quirksmode.org/js/detect.html

Once you've referenced the .js file, you can access lots of information:

//Browser Name
BrowserDetect.browser
//Browser Version
BrowserDetect.version
//Operating system
BrowserDetect.OS

Upvotes: 1

Related Questions