JavaScript: the best way to detect IE

Reading in this article I found the following code snippet:

if ('v'=='\v') { // Note: IE listens on document document.attachEvent('onstorage', onStorage, false); } 

Is this 'v'=='\v' method a great idea? Is this the shortest way to detect IE ever?

+4
source share
3 answers

If you can avoid this, do not check your browser. Function detection. This will mean that your code (most likely will) be future. In this case, for example, if you found that the browser was IE and decided to use attachEvent because of this, you would miss the fact that addEventListener (superior) is available in IE9.

In this case, check if document.addEventListener exists. If so, you have an answer.

 if (document.addEventListener) { document.addEventListener(...); } else { document.attachEvent(...); } 

Edit: the duri comment above shows that this test does not work in IE9 (according to standards), which actually means that it is a great test for addEventListener , since it is available from IE9. However, it is still much better to program certain functions, rather than specific browsers.

+10
source

You can check Trident, IE engine, as follows:

 var trident = !!window.ActiveXObject; 

As indicated on MSDN , it is only supported in IE.

+8
source

To check if the browser is Internet Explorer, use the function detection function to check documentMode :

http://msdn.microsoft.com/en-us/library/ie/cc196988%28v=vs.85%29.aspx

This code checks to see if Internet Explorer 8, 9, 10, or 11 is:

 var docMode = document.documentMode, hasDocumentMode = (docMode !== undefined), isIE8 = (docMode === 8), isIE9 = (docMode === 9), isIE10 = (docMode === 10), isIE11 = (docMode === 11), isMsEdge = window.navigator.userAgent.indexOf("Edge/") > -1; // browser is IE if(hasDocumentMode) { if(isIE11){ // browser is IE11 } else if(isIE10){ // browser is IE10 } else if(isIE9){ // browser is IE9 } else if(isIE8){ // browser is IE8 } } else { // document.documentMode is deprecated in MS Edge if(isMsEdge){ // browser is MS Edge } } 

Checking document.documentMode will only work in IE8 through IE11, since documentMode was added in IE8 and deprecated / deleted in MS Edge.

http://msdn.microsoft.com/en-us/library/ff406036%28v=vs.85%29.aspx

Hope this helps!

UPDATE

If you really need to define IE7, check out document.attachEvent :

 var isIE7 = (document.attachEvent !== undefined); if(isIE7) { // browser is IE7 } 

IE7 returns an object, but if the browser is IE11 (for example), then it will return as undefined , since IE11 does not have attachEvent .

UPDATE:

Check added for MS Edge. document.documentMode was deprecated in MS Edge . Due to the nature of MS Edge, you can check Edge/ in the User Agent. Microsoft makes it difficult to use the discovery feature in MS Edge.

+6
source

All Articles