Use JavaScript to Determine Vistor's Version of Internet Explorer

Because older versions of Internet Explorer were so awful at rendering pages, it's often important to know if your user is attempting to access your site via the infamous browser and, if so, which version of it. This simple JavaScript does the trick nicely:

1.   function ie_version_check() {
2.   	var agent = navigator.userAgent;
3.   	var iepos = agent.indexOf('MSIE');
4.   	if (iepos > -1) {
5.   		var ie_version = agent.substring(iepos);
6.   		var ppos = ie_version.indexOf('.');
7.   		ie_version = ie_version.substring(5,ppos);
8.   		ie_version = Math.round(ie_version);
9.   		return ie_version;
10.  	} else {
11.  		return -1;
12.  	}
13.  }

The logic is pretty simple. We ask for the browser info — the userAgent — from the user via JavaScript, then we look for "MSIE" (short for Microsoft Internet Explorer). If it's there, we follow up by looking for the number following that string, knowing it'll be the version number. We stop at the period, finding it most helpful to round to the nearest major version. And, if the "MSIE" string isn't there, we'll know the user isn't using IE.

Note: It's super-easy to spoof your user agent, so you can't treat the results of this method as 100% accurate. But, it works unless someone is intentionally trying to spoof it. And, if they see a poorly designed page as a result or their spoofing, that's their problem, not yours.

Back to our function…

To show that it works, we'll write a quick script to display the results on the page. Here's your own version of Internet Explorer:

Your browser doesn't have JavaScript enabled.

That bold paragraph above was generated using this code:

1.   <p id="ie_results" style="font-weight:bold;">Your browser doesn't have JavaScript enabled.</p>
2.   <script type="text/javascript">
3.   var ie_version = ie_version_check();
4.   if (ie_version < 0) { document.getElementById('ie_results').innerHTML = 'You are not using Internet Explorer.'; }
5.   else if (ie_version > 0) { document.getElementById('ie_results').innerHTML = 'You are using Internet Explorer Version ' + ie_version + '.'; }
6.   else {  document.getElementById('ie_results').innerHTML = 'Error!'; }
7.   </script>

Now that we know if the user is using Internet Explorer and, if so, which version, we can react accordingly. If you're trying to do feature detection, something like Modernizr works well, but often it's easier to just block access to a page completely for the very small percentage of people that's on super old versions of IE. Now you can.

Leave a Comment

Name and email are required. Your email will not be published.

This post was published on March 5th, 2015 by Robert James Reese in JavaScript. Before using any of the code or other content in this post, you must read and agree to our Terms & Conditions.