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:

function ie_version_check() {
	var agent = navigator.userAgent;
	var iepos = agent.indexOf('MSIE');
	if (iepos > -1) {
		var ie_version = agent.substring(iepos);
		var ppos = ie_version.indexOf('.');
		ie_version = ie_version.substring(5,ppos);
		ie_version = Math.round(ie_version);
		return ie_version;
	} else {
		return -1;

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:

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

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.



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 of use.