Detect if IE < 11 reliably - javascript

Does a reliable method for detecting IE browser version exist? So far I have tried.
IE Conditional comments, not reliable
User Agent HTTP request header, not always set
My next option was to try out javascript with something like
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName = navigator.appName;
var fullVersion = ''+parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion,10);
But will javascript always have access to this information?

One of the main features (although poorly implemented) that exists in IE11 and not earlier versions is const. So you could just create a const variable in an eval and see if an error is being thrown.
function isIE11() {
try {
eval("const x = 1;");
return true;
} catch (err) {}
return false;
}
console.log(isIE11());

You can try to refer code example below which can identify IE7, IE8, IE9, IE10, IE11 versions.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>
function GetIEVersion() {
var sAgent = window.navigator.userAgent;
var Idx = sAgent.indexOf("MSIE");
// If IE, return version number.
if (Idx > 0)
return parseInt(sAgent.substring(Idx+ 5, sAgent.indexOf(".", Idx)));
// If IE 11 then look for Updated user agent string.
else if (!!navigator.userAgent.match(/Trident\/7\./))
return 11;
else
return 0; //It is not IE
}
if (GetIEVersion() > 0)
alert("This is IE " + GetIEVersion());
else
alert("This is not IE.");
GetIEVersion();
</script>
</head>
<body>
</body>
</html>
Further, You can try to modify this code as per your own requirement.

Related

Javascript Snippet not working in Safari 11 & 12

does anyone know the reason why the following javascript snippet works in both Chrome & Firefox but not in the Safari 11 & 12 versions?
The only thing it does is take the value in the url parameter code and insert it in the url's on the page that need I want it to be in.
Are there any restrictions concerning javascript in the new Safari versions?
I can't find any info online..
<script>
window.addEventListener("DOMContentLoaded", function() {
if (window.location.href.indexOf('?code') > -1) {
var uniqueCode = window.location.search.split(/\?|&/g).filter(function(str){
return str.toLowerCase().indexOf('code') > -1
})[0].replace('code=','');
var codeLinks = document.querySelectorAll('[href*="/validate/promocode/"');
for (var i = 0; i < codeLinks.length; i++) {
var currentHref = codeLinks[i].href;
var newHref = currentHref.replace(/\/validate\/promocode\/.*\/buy\//, "/validate/promocode/" + uniqueCode + "/buy/");
codeLinks[i].href = newHref;
}
}
}, false);
</script>
I have no Mac to test this , but is it possible that Javascript is default disabled on version 11 and 12 on Mac?
Solved
The problem lies in the following line :
var codeLinks = document.querySelectorAll('[href*="/validate/promocode/"');
should be
var codeLinks = document.querySelectorAll('[href*="/validate/promocode/"]');
A small syntax error the other 4 browsers don't complain about.
Conclusion : Safari is much stricter on Syntaxerrors.

Why css class is not overridden for IE9?

I have piece of HTML code in which we are applying special css for IE9, IE10 & IE11.
<!doctype html>
<!--[if IE 9]><html data-placeholder-focus="false" lang="{%=user_locale_html}}" dir="ltr" class="ie9 lt-ie10 lt-ie11 lt-ie12 gt-ie8 gt-ie7 gt-ie6"><![endif]-->
<!--[if !(IE)]><!--><html lang="{%=user_locale_html}}" dir="{%=dir}}">
<script>
var ua = window.navigator.userAgent;
if (ua.indexOf("Trident/7.0") > 0)
document.documentElement.className='ie11 lt-ie12 gt-ie10 gt-ie9 gt-ie8 gt-ie7 gt-ie6';
else if (ua.indexOf("Trident/6.0") > 0)
document.documentElement.className='ie10 lt-ie11 lt-ie12 gt-ie9 gt-ie8 gt-ie7 gt-ie6';
if(/*#cc_on!#*/false){
document.documentElement.className='gt-ie11 gt-ie10 gt-ie9 gt-ie8 gt-ie7 gt-ie6';
}
</script>
<!--<![endif]-->
</html>
Note the code if(/*#cc_on!#*/false) {}
This code is overriding the css class applied in IE10 when we have userAgant=Trident/6.0. (Which causing me problem to override ie10 class.
But my question is, Why this code is not overriding the classes when the browser is IE9?
I know that #cc_on related stuff is not needed in the code, But i am curious to know how it is behaving differently.
Thanks!
Possible that your code is not identifying the IE 9 and that is why CSS class not get override.
I suggest you to try to refer code example below which can able to find the IE 8, IE 9, IE 10, IE 11.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>
function GetIEVersion() {
var sAgent = window.navigator.userAgent;
var Idx = sAgent.indexOf("MSIE");
// If IE, return version number.
if (Idx > 0)
return parseInt(sAgent.substring(Idx+ 5, sAgent.indexOf(".", Idx)));
// If IE 11 then look for Updated user agent string.
else if (!!navigator.userAgent.match(/Trident\/7\./))
return 11;
else
return 0; //It is not IE
}
if (GetIEVersion() > 0)
alert("This is IE " + GetIEVersion());
else
alert("This is not IE.");
</script>
</head>
<body>
</body>
</html>
Output:
Further, you can try to modify it as per your requirement may help you to solve your issue.

How to check if IE11 is in compatibility view using JS

I'd like to check if IE11 compatibility view is enabled for the current domain. Setting compatibility view is through: Tools > Compatibility View Settings.
I know this has been asked by a few a couple of years ago but looks like the answers doesn't work anymore due to recent update on IE11.
Does anyone know an alternative way to do this?
In IE versions 8-11 You can use document.documentMode. Valid values are 5, 7 (compatibility mode), 8, 9, 10, and 11 (Edge).
Setting compatibility mode in the console changes the value directly.
Loading a page with a <meta http-equiv tag changes the value
Adding a site to compatibility mode in "Tools -> Compatibility View
settings" changes the value to 7.
https://msdn.microsoft.com/en-us/library/jj676915(v=vs.85).aspx
Examples
For example if I load this page in IE11 I get documentMode of 11.
<!doctype HTML>
<body>
<p>Hello World!<p>
</body>
This page loaded in IE11 sets documentMode to 9.
<html>
<head>
<meta http-equiv="x-ua-compatible" content="IE=9"/>
</head>
<body>
<p>Hello World!<p>
</body>
</html>
If you just wanting to check if you are being run in compatibility mode you can use this script.
// Create new ieUserAgent object
var ieUserAgent = {
init: function () {
// Get the user agent string
var ua = navigator.userAgent;
this.compatibilityMode = false;
// alert (ua);
if(ua.indexOf("MSIE") == -1){
this.version = 0;
return 0;
}
if(ua.indexOf("compatible") == -1){
this.compatibilityMode = false;
return 0;
}else{
this.compatibilityMode = true;
return 0;
}
}
};
// Initialize the ieUserAgent object
ieUserAgent.init();
-OR-
/**
* Check if client is IE and in compatibility view
*
* #returns {boolean}
*/
function isIECompatibilityMode() {
var ua = navigator.userAgent;
if (ua.indexOf("MSIE") == -1) {
return false;
}
return (ua.indexOf("compatible") != -1); }

Show a message if the browser is not internet explorer 9 or greater

I would like to show my users a bar that looks like this, if:
Browser is not IE; or
Browser is IE but is version 8 or earlier
(Note that the screenshot is just for illustration - IE 9 is supported for my site.)
I found this nice jQuery plugin, but I don't want to use popups.
http://jreject.turnwheel.com/
The site where I will implement this is a Sharepoint 2013 site, so I will use a content editor webpart to include the HTML content you provide and the bar should be at the top of everything else.
Please include CSS if needed to make it look as the screenshot?
HTML
IE 9 and earlier (down to, I think, IE 4) can be identified using conditional comments in HTML.
As #Jost noted, you could use them to warn IE users on IE 8 and earlier, like this:
<!--[if lte IE 8]>
BANNER HERE
<![endif]-->
However, as IE 10 dropped support for these, you can't use them to identify non-IE browsers.
jQuery
jQuery used to include a browser detection module ($.browser), but it was removed in jQuery 1.9. If you can use an earlier version of jQuery (e.g. 1.8.3) or the jQuery Migrate plugin, then you could use this to show the banner.
if ( !$.browser.msie || $.browser.version < 9 ) {
// Add banner to the page here.
}
Browser Detection in general
Please note that browser detection is difficult. New browsers are coming out all the time, so any browser support plugin can rapidly become out of date, as can the premise on which you base your warning messages. jQuery's browser detect was the most consistently maintained, and even they gave up on it in the end.
These days, web developers are generally expected to write code that works cross-browser, and use feature-detection to deal with browsers that don't support the features they want to use.
As you're working on a SharePoint site, presumably it's for internal company use, and the company is Microsoft-centric. It sounds like you're developing the site to work in IE, and ignoring other browsers during development.
If you can reasonably expect most of your users to be on some version of IE, maybe the conditional comment warning is enough.
I found the question interesting. So i worked out a script for myself, but maybe someone else can benefit from it. So that's why I posted it as an answer. It returns an object with browser and OS information.
browser = {};
if (/edge\/[0-9]{2}/i.test(navigator.userAgent)) {
browser.agent = "edge";
browser.majorVersion = parseInt(/edge\/([0-9]{2})/i.exec(navigator.userAgent)[1]);
browser.version = /edge\/([0-9.]+)/i.exec(navigator.userAgent)[1];
} else if (/chrome\/[0-9]{2}/i.test(navigator.userAgent)) {
browser.agent = "chrome";
browser.majorVersion = parseInt(/chrome\/([0-9]{2})/i.exec(navigator.userAgent)[1]);
browser.version = /chrome\/([0-9.]+)/i.exec(navigator.userAgent)[1];
} else if (/firefox\/[0-9]{2}/i.test(navigator.userAgent)) {
browser.agent = "firefox";
browser.majorVersion = parseInt(/firefox\/([0-9]{2})/i.exec(navigator.userAgent)[1]);
browser.version = /firefox\/([0-9.]+)/i.exec(navigator.userAgent)[1];
} else if (/msie\ [0-9]{1}/i.test(navigator.userAgent)) {
browser.agent = "msie";
browser.majorVersion = parseInt(/MSIE\ ([0-9]{1})/i.exec(navigator.userAgent)[1]);
browser.version = /MSIE\ ([0-9.]+)/i.exec(navigator.userAgent)[1];
} else if (/opr\/[0-9]{2}/i.test(navigator.userAgent)) {
browser.agent = "opera";
browser.majorVersion = parseInt(/opr\/([0-9]{2})/i.exec(navigator.userAgent)[1]);
browser.version = /opera\/([0-9.]+)/i.exec(navigator.userAgent)[1];
} else if (/Trident\/[7]{1}/i.test(navigator.userAgent)) {
browser.agent = "msie";
browser.majorVersion = 11;
browser.version = "11";
} else if (/Safari\/[0-9.]+/i.test(navigator.userAgent)) {
browser.agent = "safari";
browser.majorVersion = parseInt(/Version\/([0-9]{2})/i.exec(navigator.userAgent)[1]);
browser.version = /Version\/([0-9.]+)/i.exec(navigator.userAgent)[1];
} else {
browser.agent = false;
browser.majorVersion = false;
browser.version = false;
}
if (/Windows\ NT/.test(navigator.userAgent)) {
browser.os = "windows";
var winver = parseFloat(/Windows\ NT\ ([0-9]{1,2}\.[0-9]{1})/i.exec(navigator.userAgent)[1]);
switch(winver) {
case 6.0:
browser.osversion = "Vista";
break;
case 6.1:
browser.osversion = "7";
break;
case 6.2:
browser.osversion = "8";
break;
case 6.3:
browser.osversion = "8.1";
break;
case 10.0:
browser.osversion = "10";
break;
default:
browser.osversion = false;
}
} else if (/OS\ X\ /.test(navigator.userAgent)) {
browser.os = "os x"; //
browser.osversion = /OS\ X\ [0-9]{2}_([0-9]{1,2})_[0-9]{1,2}/i.exec(navigator.userAgent)[1];
} else if (/(Linux)/.test(navigator.userAgent)) {
browser.os = "linux";
browser.osversion = false;
}
EDIT: This directly answers the OP.
I have updated Dany's answer with two updates tested in (IE 6,7,8,9,10,11), Chrome, and Edge. Primarily because the updates are very hard to read in the comments.
Pure javascript - No jQuery required
IE10 reports IE 10 vs IE 1
This now reports Edge
No specific HTML elements required to pre-exist (other than a body)
Tested in IE6, IE7, IE8, IE9, IE11, Chrome v62, and Edge
TODO: get it working properly in OSX Sierra, and iPhone
The test for edge must be first as it claims to be everything. :/
All this being said Browser detection "is what it is" and we can hope that the need for it will go away soon.
browser = {};
if (/(Edge\/[0-9]{2})/i.test(navigator.userAgent)) {
browser.agent = navigator.userAgent.match(/(Edge\/[0-9]{2})/i)[0].split("/")[0];
browser.version = parseInt(navigator.userAgent.match(/(Edge\/[0-9]{2})/i)[0].split("/")[1]);
} else if (/(chrome\/[0-9]{2})/i.test(navigator.userAgent)) {
browser.agent = navigator.userAgent.match(/(chrome\/[0-9]{2})/i)[0].split("/")[0];
browser.version = parseInt(navigator.userAgent.match(/(chrome\/[0-9]{2})/i)[0].split("/")[1]);
} else if (/(firefox\/[0-9]{2})/i.test(navigator.userAgent)) {
browser.agent = navigator.userAgent.match(/(firefox\/[0-9]{2})/i)[0].split("/")[0];
browser.version = parseInt(navigator.userAgent.match(/(firefox\/[0-9]{2})/i)[0].split("/")[1]);
} else if (/(MSIE\ [0-9]{1})/i.test(navigator.userAgent)) {
browser.agent = navigator.userAgent.match(/(MSIE\ [0-9]{1})/i)[0].split(" ")[0];
browser.version = parseInt(navigator.userAgent.match(/(MSIE\ [0-9]+)/i)[0].split(" ")[1]);
} else if (/(Opera\/[0-9]{1})/i.test(navigator.userAgent)) {
browser.agent = navigator.userAgent.match(/(Opera\/[0-9]{1})/i)[0].split("/")[0];
browser.version = parseInt(navigator.userAgent.match(/(Opera\/[0-9]{1})/i)[0].split("/")[1]);
} else if (/(Trident\/[7]{1})/i.test(navigator.userAgent)) {
browser.agent = "MSIE";
browser.version = 11;
} else {
browser.agent = false;
browser.version = false;
}
if (/(Windows\ NT\ [0-9]{1}\.[0-9]{1})/.test(navigator.userAgent)) {
browser.os = "Windows";
switch (parseFloat(navigator.userAgent.match(/(Windows\ NT\ [0-9]{1}\.[0-9]{1})/)[0].split(" ")[2])) {
case 6.0:
browser.osversion = "Vista";
break;
case 6.1:
browser.osversion = "7";
break;
case 6.2:
browser.osversion = "8";
break;
default:
browser.osversion = false;
}
} else if (/(OS\ X\ [0-9]{2}\.[0-9]{1})/.test(navigator.userAgent)) {
browser.os = "OS X";
browser.osversion = navigator.userAgent.match(/(OS\ X\ [0-9]{2}\.[0-9]{1})/)[0].split(" ")[2];
} else if (/(Linux)/.test(navigator.userAgent)) {
browser.os = "Linux";
browser.osversion = false;
}
if (browser.agent === "MSIE" && browser.version <= 9) {
var newDiv = document.createElement("div");
newDiv.innerHTML = "IE9 is not supported. You are using an UNSUPPORTED version of Internet Explorer.";
newDiv.setAttribute("style", "background-color:yellow;padding:18px;");
document.body.insertBefore(newDiv, document.body.firstChild);
} else { //TODO: Remove for Prod only added to show some flexibility and testing
var newDiv = document.createElement("div");
newDiv.innerHTML = "<b>" + browser.agent + "</b> is <i>so</i> supported. You are using version: " + browser.version + ".";
newDiv.setAttribute("style", "background-color:cyan;padding:12px;");
document.body.insertBefore(newDiv, document.body.firstChild);
}
I like the simple conditional html. (Simpler always seems better.)
Another more comprehensive javascript alert can be found at: http://www.browser-update.org
Checking if browser engine is Trident 6+ (IE 9, 10, 11) should do (demo):
(function () {
var trident = {
string: navigator.userAgent.match(/Trident\/(\d+)/)
};
trident.version = trident.string ? parseInt(trident.string[1], 10) : null;
if (!trident.string || trident.version < 6) {
document.body.innerHTML = '<div class="alert">Not supported.</div>' +
document.body.innerHTML;
}
})();
However, the sniffing may break in IE 11 final or future versions if Microsoft will decide to change userAgent string.
You could use conditional compiling in conjunction with conditional comments
Here a short overview of how this could work.
Always show the bar
Set a flag in javascript. IEMinor=false
Set the flag to true if IE <= 9, by using a script tag and conditional comments
Use conditional compiling to hide the bar if #_jscript_version > 9 (actually not needed) and IEMinor===false
<div id="bar"><center>Not Supported</center></div>
<script>
var IEMinor = false;
</script>
<!-- [if lte IE 9] -->
<script>var IEMinor = true</script>
<!-- <![endif] -->
<script>
/*#cc_on #*/
/*#if (#_jscript_version > 9)
if (!IEMinor)
document.getElementById("bar").style.display = "none";
/*#end #*/
</script>
I was too lazy to add the script type...
Here is an example on JSBin which doesn't show the bar in IE 10+ (untested). And shows it in other cases.
Note: I didn't make it look exactly like in the screenshot, you should get that part working
Edit: Using the browsermode of IE to test against IE<10 seems to work
Edit2: Whoops i thought from the picture IE9 is unsupported too, to allow IE9 change lte IE 9 to lt IE 9 and #_jscript_version > 9 to >= 9
Actually in SharePoint (OP mentioned that) there is a built-in variable browseris. It's available in the global window scope. Answering OP question:
Browser is not IE;
use browseris.ie
Browser is IE but is version 8 or earlier
use browseris.ie8down
(tested in SP2013 on-prem)
This is tested for IE 10 and 11. Head on to this link for more description.
<div id="noSupport"></div>
<script>
function isIE() {
return /Trident\/|MSIE/.test(window.navigator.userAgent); // IE 10 and IE 11
}
if (isIE()) {
document.getElementById('noSupport').innerHTML = 'IE not supported'
}
</script>
check this code, its working as expected.
if (navigator.userAgent.includes('Trident')) {
alert('This site is not supported by your Internet Explorer, please use Microsoft Edge or Google Chrome.');
}
I don't suggest you to use client side as some browsers might trick you by passing wrong values to pass website tests.
So i guess your using PHP as a server side you can detect the browser using the get_browser() function that give you a lot of information about the browser here is a nice turtoeial:
Part 1:
http://thenewboston.org/watch.php?cat=11&number=67
Part 2:
http://thenewboston.org/watch.php?cat=11&number=68
if your using another language all server side language has this functunality just google it or reference some sort of a turtorial
From the client side you can detect if it is compatible like that:
function Is_Compatible(){
var browser = navigator.appName;
var Fvar = document.getElementById('test').style.borderRadius;
if(browser !== 'Microsoft Internet Explorer'){
return false;
}
if(Fvar == undefined){
//Not IE9+
return false;
}else{
//Is IE9+
return true;
}
}
if(Is_Compatible() == true){
alert('Compatible');
}else{
alert('uncompatible');
}
HTML:
<div style="border-radius:20px;opacity:0;z-index:-500;" id="test"></div><!--It willl not inflect your design-->
FIDDLE:
Test it and it works:
http://jsfiddle.net/Z7fvb/

getElementsByTagName() behaves differently in IE and FF

I am new to JavaScript, trying to figure out a tag information value. GWT Code is as follows..
public static native boolean isToolBarInstalled() /*-{
alert("Validating the toolbar installed.");
var metas = document.getElementsByTagName('head')[0].getElementsByTagName('meta');
var i;
alert ("Meta length: "+metas.length);
for (i = 0; i < metas.length; i++){
alert("Value: "+metas[i].value);
if (metas[i].getAttribute('name') == "toolbar"){
return true;
}
}
return false;
}-*/;
FF return true whereas IE returns false, for the same page? Any clue/suggestions would be helpful.
WM.
HTML is too huge to post, here is a snippet of the code..
<html>
<head>
....
<title>My App</title>
<meta name="toolbar" content="1.0">
</head>
<body>
.....
</body>
<html>
Works for me in IE7.
Check you haven't got any text content before the <meta> end-tag other than simple whitespace.
If you have any non-whitespace text in or before <html> or <head>, the browser will decide that you meant to open the <body> to contain the text. (This is actually valid in non-XHTML HTML, as the </head> end-tag and the <body> start-tag are optional.) That means closing the <head> section, so the number of <meta> tags inside <head> will be 0.
In any case you might as well say just:
var metas= document.getElementsByTagName('meta');
as the bit about checking they're in <head> is redundant for a valid document; that's the only place <meta> is allowed to appear.
alert("Value: "+metas[i].value);
There's no .value on <meta>, do you mean .content?
if (metas[i].getAttribute('name') == "toolbar"){
Use metas[i].name. There's no reason to use getAttribute/setAttribute on an HTML document and there are problems with it on IE.
Try this:
element.attributes[value].nodeAttribute;
As explained here:
The getAttribute() method will return
"null" in Internet Explorer when
trying to get the for attribute of a
label element.
Might be the same issue...
Well look:
Example
Source
In this example it is working on IE.
function isToolBarInstalled() {
alert("Validating the toolbar installed.");
var metas = document.getElementsByTagName('head')[0].getElementsByTagName('meta');
var i;
alert ("Meta length: "+metas.length);
for (i = 0; i < metas.length; i++){
alert("Value: "+metas[i].value);
var attr = metas[i].getAttribute('name');
// IE workaround
if (attr == null)
{
attr = metas[i].attributes["name"];
if (attr != null) attr = attr.nodeValue;
}
if (attr == "toolbar")
return true;
}
return false;
}
alert( "Is installed: " + isToolBarInstalled() );

Categories