browser detection in javascript - javascript

I need to show a different webpage when i open my website in IE6 and below version.
Need to show fbrowser.html file when my website opens in IE6 and below versions.
Please suggest!!

In head:
<!--[if lte IE 6]>
<meta http-equiv="refresh" content="0; url=fbrowser.html">
<![endif]-->
Sorry, no javascript needed.

You could consider using http://api.jquery.com/jQuery.browser/

According to this answer, you can try somethiing like the following:
<script type="text/javascript">
// <![CDATA[
var BrowserCheck = Class.create({
initialize: function () {
var userAgent = navigator.userAgent.toLowerCase();
this.version = (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1];
this.safari = /webkit/.test(userAgent) && !/chrome/.test(userAgent);
this.opera = /opera/.test(userAgent);
this.msie = /msie/.test(userAgent) && !/opera/.test(userAgent);
this.mozilla = /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent);
this.chrome = /chrome/.test(userAgent);
}
});
// ]]>
</script>

Related

Add Class for different browsers

I know this is an old question. I want to add browser specific classes for different browsers mainly for IE versions.
I used below mentioned code:
<!--[if IE 7 ]> <html dir="ltr" lang="en-US" class="ie ie7 lte8 lte9"> <![endif]-->
<!--[if IE 8 ]> <html dir="ltr" lang="en-US" class="ie ie8 lte8 lte9"> <![endif]-->
<!--[if IE 9 ]> <html dir="ltr" lang="en-US" class="ie ie9 lte9"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--><html dir="ltr" lang="en-US" class="not-ie"><!--<![endif]-->
Here problem is now conditional comments are gone form ie10+ and I want specific class for all ie versions. Even it would great if I also get class for webkit and moz browsers.
Purpose of this to remove all css hacks from my existing stylesheet.
I want something should work like this and JScript solution is also acceptable.
<!--[if IE 7 ]> <html dir="ltr" lang="en-US" class="ie ie7 lte8 lte9"> <![endif]-->
<!--[if IE 8 ]> <html dir="ltr" lang="en-US" class="ie ie8 lte8 lte9"> <![endif]-->
<!--[if IE 9 ]> <html dir="ltr" lang="en-US" class="ie ie9 lte9"> <![endif]-->
<!--[if IE 10 ]> <html dir="ltr" lang="en-US" class="ie ie10"> <![endif]--> <!--no more work for 1e10+ -->
<!--[if IE 11 ]> <html dir="ltr" lang="en-US" class="ie ie11"> <![endif]--> <!--no more work for 1e10+ -->
<!--[if !IE]><!--><html dir="ltr" lang="en-US" class="not-ie"><!--<![endif]-->
In javascript you can use the navigator.userAgent variable and check if it match the IE user agent (MSIE ** or Trident/**)
Warning : Trident is the new way to check for IE:
var newIEReg = new RegExp("Trident\/([0-9]+)\.0")
var oldIEReg = new RegExp("MSIE ([0-9]+)\.[0-5]+")
var ieVersion = -1;
if(navigator.userAgent.match(newIEReg))
{
ieVersion = parseInt(newIEReg.$1) + 4;
}
else if(navigator.userAgent.match(oldIEReg))
{
ieVersion = parseInt(oldIEReg.$1);
}
Use following JavaScript code, it will add IE version class in HTML tag:
Source:
(function () {
var v = 3,
div = document.createElement('div'),
all = div.getElementsByTagName('i'),
browser,
isIE;
while ( div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->', all[0]);
v = v > 4 ? v : document.documentMode;
if (v) {
browser = " ie"
for(var i = 5; i<12; i++){
if(v < i) {
browser += ' lte-ie' + i;
}else if (v > i) {
browser += ' gte-ie' + i;
}else if (v == i) {
browser += ' ie' + i;
}
}
isIE = {
"version" : v
}
} else {
browser = ' not-ie';
isIE = false;
}
document.documentElement.className += browser;
window.ie = isIE;
}());
Minified:
(function(){for(var a=3,b=document.createElement("div"),c=b.getElementsByTagName("i");b.innerHTML="\x3c!--[if gt IE "+ ++a+"]><i></i><![endif]--\x3e",c[0];);if(a=4<a?a:document.documentMode){b=" ie";for(c=5;12>c;c++)a<c?b+=" lte-ie"+c:a>c?b+=" gte-ie"+c:a==c&&(b+=" ie"+c);a={version:a}}else b=" not-ie",a=!1;document.documentElement.className+=b;window.ie=a})();
Comment:
Since the script is supporting IE5 and above, I'm keeping all version detection. It may not be useful for you but someone else can find it helpful. And there is no harm of having extra CSS classes.
Each browser has a user agent, so you can use something like following:
var user_agent = navigator.userAgent;
if(user_agent=="BROWSER_USER_AGENT"){
// your code
}
The user agents list is available online.
Main Solution:
I forgot where I got this function so I can't properly give credit to it but it works really well:
function getInternetExplorerVersion() {
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat(RegExp.$1);
}
if (rv > -1) {
return rv;
}
else {
return 0;
}
}
So what you can do with this is:
if(getInternetExplorerVersion() == 6) {
$('head').append('<link id="styles" rel="stylesheet" type="text/css" href="/ie6Styles.css" />');
}
Or something along those lines.
Other Solutions:
For other browsers you can also do the following:
var is_chrome = navigator.userAgent.indexOf('Chrome') > -1;
var is_explorer = navigator.userAgent.indexOf('MSIE') > -1;
var is_firefox = navigator.userAgent.indexOf('Firefox') > -1;
var is_safari = navigator.userAgent.indexOf("Safari") > -1;
var is_Opera = navigator.userAgent.indexOf("Presto") > -1;
var is_Silk = navigator.userAgent.indexOf("Silk") > -1;
var is_Kindle = navigator.userAgent.indexOf("Kindle") > -1;
and I prefer these for iPads/iPods/iPhones:
if (navigator.userAgent.match(/iPad/)) { iPad = true; }
if (navigator.userAgent.match(/iPhone/) || navigator.userAgent.match(/iPod/)) { iPhone = true; }
Modernizr works great, but it only lets you know if a browser can handle certain features. Sometimes you actually have to target a specific browser for other fixes, like styles. This is where any of the above solutions can come in really handy. Good luck and let me know if you have any questions.
You can opt for some sort of JavaScript detection, but that would be beating around the bush and not dealing with the problem directly. It is what's usually called a band aid fix.
You shouldn't have to use hacks for IE11, IE10 and even IE9. They are fairly competent and standards compliant browsers.
I would look into solving the issues at their core - clean up and simplify your markup, make sure it validates, all tags are closed, declare dimensions, use a CSS reset, clear your floats etc.
That's if your issues are layout related.
If they aren't and you are using some bleeding edge functionality that's not supported everywhere, use feature detection - not browser detection.
This is the exact reason why Microsoft stopped supporting conditional comments. This is also why they changed the User Agent in IE11 to completely omit the fact that the browser is in fact IE.
They did it to encourage proper feature detection i.e Modernizr and not UA sniffing, as it's a bad idea.
See this JSFiddle for an example.
This supports IE 7 - 11, WebKit (Chrome, Safari etc.) and Gecko (Firefox etc.).
Detect the user agent with JavaScript and apply a class to the body depending on which browser:
<script>
var ua = navigator.userAgent;
if (!ua.contains("MSIE")) { // If it doesn't contain MSIE
document.body.classList.add("not-ie");
if (ua.contains("(Windows NT 6.3; Trident/7.0; rv:11.0)")) {
// IE11 pretends to not be IE and doesn't contain MSIE in the
// default user agent, but it contains the string above
document.body.classList.remove("not-ie");
document.body.classList.add("ie", "ie11");
} else if(ua.contains("Gecko")) {
document.body.classList.add("gecko");
} else if(ua.contains("WebKit")) {
document.body.classList.add("webkit");
}
} else {
document.body.classList.add("ie");
if (ua.contains("11.0")) {
// Just in case we're using an alternative user agent
document.body.classList.add("ie11");
} else if (ua.contains("10.6") || ua.contains("10.0")) {
document.body.classList.add("ie10");
} else if (ua.contains("9.0")) {
document.body.classList.add("ie9");
} else if (ua.contains("8.0")) {
document.body.classList.add("ie8");
} else if (ua.contains("7.0")) {
document.body.classList.add("ie7");
};
};
</script>
Some references to get you going:
http://blog.tcg.com/tcg/2012/08/mobile-browser-detection-and-redirects.html
Here are a few other sites to check:
http://blogs.msdn.com/b/ie/archive/2011/04/15/the-ie10-user-agent-string.aspx
How to write specific CSS for mozilla, chrome and IE
http://bastianallgeier.com/css_browser_selector/

Print external page without open it

I want print a page without open it on all major browsers. (Safari, IE, firefox, Chrome and Opera)
I tried that but doesn't work on firefox (Error : Permission denied to access property 'print') :
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
<link rel="alternate" media="print" href="print.php">
<script type="text/javascript">
function impression() {
window.frames[0].focus();
window.frames[0].print();
}
</script>
</head>
<body>
<iframe height="0px" src="print.php" id="fileToPrint" style="visibility: hidden"></iframe>
Imprimer
</body>
</html>
This code works on Chrome.
I want one thing like that for all browsers to mention but I don't know how.
Is there another way to do that?
Create an iframe, hide it, and then call the proper print functions. The execCommand should work for all versions of IE.
Mind you: $.browser won't work for newer versions of jQuery and should be avoided. Use your preferred way of detecting features.
var ifr = createIframe();
ifr.hide();
if ($.browser.msie) {
ifr.contentWindow.document.execCommand('print', false, null);
} else {
ifr.contentWindow.focus();
ifr.contentWindow.print();
}
This was developed for IE, FF and Chrome. I have no idea how well this will work for Safari and Opera, but it might give you some ideas.
Edit: as adeneo correctly pointed out, $.browser is deprecated and should be avoided. I updated my statement. I'll leave my code untouched, as it still expresses the correct intent.
You can try this code, but it's Javascript ;
<script language="JavaScript">
var gAutoPrint = true; // Tells whether to automatically call the print function
function printSpecial()
{
if (document.getElementById != null)
{
var html = '<HTML>\n<HEAD>\n';
if (document.getElementsByTagName != null)
{
var headTags = document.getElementsByTagName("head");
if (headTags.length > 0)
html += headTags[0].innerHTML;
}
html += '\n</HE>\n<BODY>\n';
var printReadyElem = document.getElementById("printReady");
if (printReadyElem != null)
{
html += printReadyElem.innerHTML;
}
else
{
alert("Could not find the printReady function");
return;
}
html += '\n</BO>\n</HT>';
var printWin = window.open("","printSpecial");
printWin.document.open();
printWin.document.write(html);
printWin.document.close();
if (gAutoPrint)
printWin.print();
}
else
{
alert("The print ready feature is only available if you are using an browser. Please update your browswer.");
}
}
</script>

Javascript - Changing button image depending on device

I am trying to display the correct button and link depending on what device the user browses to a page on. If android display android app store button if ios display apple store button.
I cannot seem to get it to swap at all even though im making the function default to swap it from android to apple button.
Here is the code:
<html>
<head>
<script type="text/javascript">
var uagent = navigator.userAgent.toLowerCase();
var apple = "/images/ios.jpg";
var android = "/images/android.jpg"
function DetectDevice() {
var but = document.getElementById("AppButton");
if(useragent.search("iphone") || useragent.search("ipod") || useragent.search("ipad")) {
toswap.src = apple;
alert("apple");
} else if(useragent.search("android")) {
toswap.src = android;
alert("android");
}
but.src = apple;
}
DetectDevice();
</script>
<title>Device Detection</title>
</head>
<div id="butttons">
<img src="images/android.jpg" name = "AppButton" id="AppButton"/>
</div>
Two issues:
First, your function needs to run after the button has loaded because
document.getElementById("AppButton");
is returning nothing at the moment.
Secondly, you should probably change 2 instances of toswap.src to but.src.
I don't know where var toswap refers to. Try this:
var uagent = navigator.userAgent.toLowerCase();
var apple = "/images/ios.jpg";
var android = "/images/android.jpg"
function DetectDevice() {
var but = document.getElementById("AppButton");
if(useragent.search("iphone") || useragent.search("ipod") || useragent.search("ipad")) {
but.src = apple;
alert("apple");
} else if(useragent.search("android")) {
but.src = android;
alert("android");
} else{
but.src = apple; // this is default
}
}
</script>
<div id="butttons">
<img src="images/android.jpg" onload="DetectDevice();" name = "AppButton" id="AppButton"/>
</div>
useragent is not defined either. You may have meant to use uagent which you defined, or you may have meant to rename your variable.

Get IE Version + Add Class to body

I am trying to find which version of IE people are using and adding a class to the body tag depending on which browser.
the code i have is
if (navigator.appName == "Microsoft Internet Explorer") {
//Set IE as true
ie = true;
//Create a user agent var
var ua = navigator.userAgent;
//Write a new regEx to find the version number
var re = new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})");
//If the regEx through the userAgent is not null
if (re.exec(ua) != null) {
//Set the IE version
ieVersion = parseInt(RegExp.$1);
}
}
else {
ie = false;
}
function ieTag() {
if (ie == true) {
if (ieVersion == 7) {
$('body').addClass('IE7');
}
}
if (ie == true) {
if (ieVersion == 8) {
$('body').addClass('IE8');
}
}
if (ie == true) {
if (ieVersion == 9) {
$('body').addClass('IE9');
}
}
}
and i am using this to call the function
<script type="text/javascript">
$(document).ready(function () {
//IE Version Control
ieTag();
});
</script>
but i am only picking up IE 9 for some reason, i have had this script working before so i really dont understand whats gone wrong!!!
i have even tried using this script
function ieTag() {
if (ie == true) {
$('body').addClass('IE' + ieVersion);
}
}
but still only picking up IE9
I ma using IE( and the developer tools to change version (which both of these scripts has worked on before)
This is probably not the answer you are looking for, but it does seem like the simplest solution:
<!--[if lt IE 7]> <body class="ie6"> <![endif]-->
<!--[if IE 7]> <body class="ie7"> <![endif]-->
<!--[if IE 8]> <body class="ie8"> <![endif]-->
<!--[if IE 9]> <body class="ie9"> <![endif]-->
<!--[if gt IE 9]> <body class="ie10+"> <![endif]-->
<!--[if !IE]><!--> <body> <!--<![endif]-->
of course added in the HTML where your body tag is supposed to start.
You could use conditional comments so that it doesn't affect other browsers.
<!--[if IE 6]>
<script>
$(document).ready(function(){
$("body").addClass("ie-6");
});
</script>
<![endif]-->
<!--[if IE 7]>
<script>
$(document).ready(function(){
$("body").addClass("ie-7");
});
</script>
<![endif]-->
<!--[if IE 8]>
<script>
$(document).ready(function(){
$("body").addClass("ie-8");
});
</script>
<![endif]-->
<!--[if IE 9]>
<script>
$(document).ready(function(){
$("body").addClass("ie-9");
});
</script>
<![endif]-->
You don't need JavaScript for this.
<!--[if IE 9]>
<body class='ie9'>
<![endif]-->
<!--[if IE 8]>
<body class='ie8'>
<![endif]-->
etc. For normal browsers you do:
<!--[if IE]><!-->
<body class='normal'>
<!--<![endif]-->
The Reason why the js in the question failed in IE 7 and IE 8 was the fact i had included the script using application/javascript rather than text/javascript,
the reason is doesn't work with application/javascript is because this is a new way of including the script that only modern browsers support and older browsers does not support this method, hence IE 7 & 8 failing.
If you have jQuery you can add ie class to body like this
$(function(){
if ($.browser.msie && $.browser.version == 8) {
$('body').addClass('ie8');
}
});

Does not work window.onload in IE8

I have a pretty simple image switcher, which I use for manual images switcher and for carousel. In IE 8 it works strange. In carousel scenario image switches just once, thereafter it's dies. But (!) when I implemented Firebug Lite and try to trace - it's works well, only with firebug on... I tried some tricks, I found, but it's all to no purpose. I have no idea what caused this kind of behavior. How to fix it?
js
function toSlide(wrapper, options){
var active = $('#' + wrapper + ' div.active');
var slide;
var direction;
if (active.length === 0){
active = $('#' + wrapper + ' div:last');
}
if (options === null) {
options = {};
options.reverse = false;
options.animate = false;
} else {
options.reverse = options.reverse === null ? false : options.reverse;
options.animate = options.animate === null ? false : options.animate;
}
direction = options.reverse === true ? active.prev() : active.next();
slide = direction.length ? direction : $('#' + wrapper + ' div:first');
if (options.animate === true){
active.addClass('last-active');
slide.addClass('active')
.css({opacity:0.0})
.animate({opacity:1.0}, 1000, function() {
active.removeClass('active last-active');
});
} else {
slide.addClass('active');
active.removeClass('active');
}
}
function startSlideShow() {
setInterval(function(){ toSlide('slideshow', {'animate': true}); }, 5000);
};
window.onload = function() {
if (document.location.pathname == '/'){startSlideShow();};
};
html in head
<!--[if IE 8 ]>
<link rel="stylesheet" href="{{ MEDIA_URL }}css/ie8.css" type="text/css" media="screen, projection" /> <html lang="en" class="no-js ie8">
<script defer src="ie_onload.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="{{ MEDIA_URL }}js/jquery-1.6.2.js"%3E%3C/script%3E'))</script>
<script type="text/javascript" src="http://fbug.googlecode.com/svn/lite/branches/firebug1.3/content/firebug-lite-dev.js"></script>
<![endif]-->
in bottom of html
<!-- Grab Google CDN's jQuery. fall back to local if necessary -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<!-- <script>!window.jQuery && document.write(unescape('%3Cscript src="{{ MEDIA_URL }}js/jquery-1.4.2.js"%3E%3C/script%3E'))</script> -->
<!-- scripts concatenated and minified via ant build script-->
<script src="{{ MEDIA_URL }}js/plugins.js"></script>
<script src="{{ MEDIA_URL }}js/script.js"></script>
<!-- end concatenated and minified scripts-->
Accessing console in FF without Firebug open or in IE will result in an error that will block the rest of your JS from executing. If you want to leave calls to console in, you should implement them like one of the following:
try { console.log('blah'); } catch(e) {}
// or
if (typeof console != 'undefined') console.log('blah');
Or use a custom built logging function that implements something like the above.
The cause was non-functional window.onload in IE8. I did right trick but made stupid mistake. So, I fixed it:
was
<!--[if IE 8 ]>
<script defer src="ie_onload.js"></script>
<![endif]-->
is now
<!--[if IE 8 ]>
<script defer src="{{ MEDIA_URL }}js/ie_onload.js"></script>
<![endif]-->
in ie_onload.js
document.body.onload = function() {
imageViewer();
// and other functions
};

Categories

Resources