is there a way to disable a certain script for all ie browsers?
You can make use of conditional compilation to determine if the client is using MSIE.
var IE = /*#cc_on!#*/false;
which can be used as
if (IE) {
// IE.
} else {
// Others.
}
Only in IE, the ! will be compiled and taken in the expression, resulting in a new expression !false, which is logically true. This works better than $.browser.msie because it can be fooled by the useragent and also better than document.all because it would affect certain Opera versions as well.
That said, what is it you're trying to disable? You can on the other hand also make use of feature detection. Here's a discussion about this: Browser detection versus feature detection
I wouldn't recommend this, but:
if(!$.browser.msie) {
//non IE script
}
I would fix the script to work in IE, or exclude it based on some feature the browser doesn't support...not just because it's IE. With any browser a feature could be added via an update tomorrow, and your script would still exclude it. See $.support for more on feature detection.
Excluding something from running because "it isn't supported" is a perfectly valid scenario. However, excluding something because "IE doesn't support it...when I wrote this code" isn't a good approach. Instead, check if the feature that you need is present, and the user gets the richest experience possible in their current browser.
You could not include the javascript at all for IE browsers using Microsoft's recommended way of inserting a conditional comment:
<!--[if !IE]>
<script src="myscript.js" type="text/javascript"></script>
<![endif]-->
or simply wrap the code you want to exclude in the comment.
If you're speaking of IE 6, you can crash it by calling this function :
function crash_IE6() {for(x in document.open);}
Seriously, the most use way of deteting IE is checking the presence of document.all... but it still isn't a good thing.
You should nerver check what browser your script is running on... you should just check the presence of the needed methods.
Related
I was just forced into a browser upgrade (IE8 to IE11) while in the middle of testing. I've lost some essential functionality with some javascript that suddenly doesn't work in my .NET site.
This section of the code was written when I was in grade school, so I'm not extremely familiar with it, but what seems to be the problem is a call to form.all. I have to assume that call was built into javascript at some point - there's no definition for it in the code.
There are 7 "if statements" that use form.all and they are all written the same way:
if(form.all(cTag + "PersonNum") != null)
form.all(cTag + "PersonNum").value = personNumber;
The error:
JavaScript runtime error: Object doesn't support property or method 'all'
In newer versions of JavaScript, is there a version of form.all that performs the same action? All I really need is for someone to point me in the right direction.
A weird note: the same JavaScript code IS working in production on IE11
EDIT Ok, I found a line that was minimized. It looks like form is a created variable.
var form = document.forms(0);
EDIT2 Compatibility view/mode was the solution after all. I had added our production site's domain to the compatibility list and didn't think about it; adding 'localhost' fixed the issue. You just have to set it to the right domain first for it to work :)
Check the browser compatability mode when your running in production it's probally on IE8.
You can use obj.getElementsByTagName("*")
You could also add an All method to the prototype if it's not there.
IE introduced an all property for certain DOM objects (e.g. document) but it was never part of any W3C standard. It allowed access to DOM objects by name or ID using:
var element = document(elementNameOrID);
or
var element = document[elementNameOrID];
that is, it is a property that could use the same syntax as a method. Neat. Some other browsers supported it for compatibility, but it pretty much went out of use with IE 6 (not sure when IE started supporting getElementById, I think it was IE 5). But IE continued to think name and ID attributes were the same thing until IE 8 in standards mode.
Support for all has been dropped from IE 11 in standards mode.
If form is a reference to a form element, and cTag + "PersonNum" is the name of a form control, then the simplest fix is to change:
form.all(cTag + "PersonNum").value
to
form[cTag + "PersonNum"].value
which takes advantage of named form controls being made properties of the form that contains them. This behaviour is standardised and supported by browsers from the very beginning (i.e. every where) and is future proof (it's not going to change).
I want to identify if the broswer is IE then goto if block, other browser to else block in Java script.
I have one code here,
var browserName=navigator.appName;
if(browserName == "Microsoft Internet Explorer"){
IE code
}
else{
Other code
}
but i want to know is there any other way of implementing it?
Rather than do browser sniffing, you should do feature detection. Later versions of IE may support standards compliant stuff that in older versions you needed to work around or use MS-specific stuff.
Microsoft themselves have written up about the best way to do this and provide examples of both bad code (via sniffing) and good code (via detection). Make sure you go down the "good code" route.
I just started using this script to identify browser, version, and OS:
http://www.quirksmode.org/js/detect.html
If you are needing to use different code based on browser support for certain objects or methods, it's usually better to use object or method detection instead of browser detection. I use the browser detection for collecting statistics on my users, not for enabling or disabling features.
Quirksmode has a short article about why you don't use browser detection this way: http://www.quirksmode.org/js/support.html It's also linked from the browser detection script.
I found that This task is quite difficult as browsers all have similar names and different userAgent strings, so this is my Conditional statement to identify browsers.
I used this to identify the browser for different style sheets.
function styc()
{
var str = navigator.userAgent;
var res = navigator.userAgent.match(/Trident/);
var res2 = navigator.userAgent.match(/Firefox/);
if(res=="Trident"||res2=="Firefox")
{
//alert(navigator.userAgent);//for testing
document.getElementById('IE_fix').setAttribute("href", "IE_fix.css");
}
else
{
//alert("no");//for testing
document.getElementById('IE_fix').setAttribute("href", "mt_default.css");
}
}
Find a unique word in the userAgent string match it and check if the condition is true or not true depending on what you are doing.
The unique word I found for IE is Trident, and also identifies IE versions according to MicroSoft(not positive on this).
I want to include a JavaScript file only if the browser is not IE. Is there any way to do this?
Update 2022:
Some options for you:
Have your server look at the User-Agent header and send different HTML to Internet Explorer vs. other browsers.
Pros:
No client-side solution required.
Cons:
Relying on User-Agent strings is notoriously error-prone, and they can be spoofed or entirely absent.
Sniff navigator.userAgent and either output a script tag or not depending on what you find.
Pros:
No server-side requirement.
Cons:
Same as #1: Relying on User-Agent strings is notoriously error-prone, and they can be spoofed or entirely absent.
Some people have an issue with outputting script tags from code, particularly via document.write, but depending on your use case document.write may be unavoidable (e.g., do you need the script there before some other script, etc.).
Sniff for something in the JavaScript runtime that only Internet Explorer has, and output a script tag or not based on what you find.
Pros:
No server-side requirement.
No user-agent sniffing.
Cons:
The issue some people have with dynamically adding script tags.
I'd probably look at #3. For instance, any even vaguely modern browser has the Symbol function. Internet Explorer does not. So:
if (typeof Symbol !== "undefined") {
document.write("<script src='./your-non-ie-script.js'><\/script>");
// Or if you prefer
let script = document.createElement("script");
script.src = "./your-non-ie-script.js";
document.activeElement.parentNode.appendChild(script);
}
Symbol is just one example, IE lacks Reflect, Proxy, and a few others from ES2015 that everything else has now...
(Not sure why I didn't mention this in 2013!)
Update 2013: IE10+ don't support conditional comments anymore.
You can do it with IE's conditional comments, like so:
<![if !IE]>
<script src="your-non-IE-script.js" type="text/javascript"></script>
<![endif]>
Note that the above is processed by non-IE browsers because the conditional is not an HTML comment, but a processing instruction, so the bit in the middle is processed by non-IE browsers. IE sees the conditional and skips over the content because it understands the conditional means "Not you, move along."
If you want to do something only for IE, you use a form that's similar, but uses HTML comments instead (with the --) because that's the only way you can rely on other browsers ignoring the contents. IE knows to pay attention to them, even though they're comments. More on the link above.
Note that there's a page load speed implication on IE (not the other browsers) when you use conditional comments (they temporarily block download of other resources), more here: http://www.phpied.com/conditional-comments-block-downloads/
You can use an IE conditional comment.
To get something that will show up in browsers other than IE, but not in IE, and which will still validate, you can use:
<!--[if !IE]>-->
<script src="..."></script>
<!--<![endif]-->
First, a note: This isn't really a good practice. If possible, you should strive to design your website in a browser-agnostic way, so that it works consistently across all browsers without the need to maintain hacks and tricks for browser-specific problems.
But if you really want to do this, it's easiest to include a file only if the browser is IE:
<!--[if lt IE 7]>
<script type="text/javascript" src="global.js"></script>
<![endif]-->
(Includes the file only if the browser is IE6 or less.)
However, if you really want to do it the other way around, here are some of your options:
Use server-side browser sniffing to process the browser before the page is drawn. That is, use a server-side language (Java, PHP, whatever) to determine what the browser is (usually through the user agent string) and then conditionally include your JS files that way. (For example, you can use PHP's get_browser function.)
Use client-side browser sniffing to call another JS file if the browser is not IE. You can determine the browser using JavaScript itself, and then insert another JS file into the page if the browser is anything but IE. (For example, you can use jQuery's browser function.)
T.J.'s answer provides a way of doing it with I.E.'s conditional comments as well.
It's lesser known than conditional comments, but I thought I'd mention that you can also use an IE feature called conditional compilation - see http://msdn.microsoft.com/en-us/library/7kx09ct1%28VS.80%29.aspx
This example comes from their docs:
/*#cc_on #*/
/*#if (#_jscript_version >= 5)
document.write("JScript Version 5.0 or better.<BR>");
#else #*/
document.write("You need a more recent script engine.<BR>");
/*#end #*/
You can do that totally different way [inserting something ONLY if IE] using Conditional Comments, maybe that would help you.
http://en.wikipedia.org/wiki/Conditional_comment
Yes, conditional scripts for IE is your answer:
<!--[if lt IE 7 ]>
<script src="/js/my_ie_script.js"></script>
<![endif]-->
How about turning it around? If this is a possibility you can use IE's conditional comments: http://www.quirksmode.org/css/condcom.html
Otherwise you could sniff user-agents but this is considered 'bad practice'.
Here's an solution working in 2022
<html>
<head>
<script>
// Test if running in Internet Explorer or not
function isIE () {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1 || myNav.indexOf('trident') != -1) ? true : false;
}
if (isIE()) {
var script = document.createElement('script');
script.src = "https://unpkg.com/core-js-bundle#3.6.5/minified.js";
document.head.appendChild(script);
}
</script>
</head>
<body>
</body>
</html>
I am interested if which would be the best place to detect the client's user-agent, client-side (javascript) or server-side? I brought up the question due to the fact that some IE8 users are getting a message saying they're using IE6.
The short and correct answer is : do not use anything that relies on UserAgent sniffing.
To reliable be able to adjust code paths you should test for the specific 'thing' that the codepath is adjusted for, primarily features. This is called Feature Detection.
So if feature X is supported we do this, if not we do that.
Deducing if a feature is supported based on which UserAgent is present will rapidly fail, especially when new browsers come to the marked.
Take the following example, which can actually be found in several major libraries (!)
if (isIE8) {
// use new feature provided by IE8
} else if (isIE7) {
// use not so new feature provided by IE7 (and IE8)
} else {
// use fallback for all others (which also works in IE7 and IE8)
}
What do you think happens when IE9 comes along?
The correct pattern in this case would be
if ("addEventListener" in foo) {
// use DOM level 2 addEventListener to attach events
foo.addEventListener(...
} else if ("attachEvent" in foo) {
// use IE's proprietary attachEvent method
foo.attachEvent(...
} else {
// fall back to DOM 0
foo["on" + eventName] = ....
}
The User-agent available on both sides should be the same, unless there's funny stuff going on, which normally isn't.
If you want to show a message to IE6 users, I suggest you use conditional comments. They're an IE-specific feature and work very well for detecting IE versions.
The information found through client or server-side detection is basically the same.
Keep in mind it is extremely easy to spoof what browser you're in. There is no fail-safe way to detect all browser types accurately.
i don't know how you're checking for the user agent, but i'd do this way:
<%=
case request.env['HTTP_USER_AGENT']
when /Safari/
"it's a Mac!"
when /iPhone/
"it's a iPhone"
else
"i don't know :("
end
%>
checking directly in the user request seems to be the most consistent way to verify the user browser. And the request.env is avaliable in your controller and views, so you could pass this to rjs if needed.
For those who need to get the actual user-agent using JavaScript, you can use navigator.userAgent
As the title states, I'd be interested to find a safe feature-based (that is, without using navigator.appName or navigator.appVersion) way to detect Google Chrome.
By feature-based I mean, for example:
if(window.ActiveXObject) {
// internet explorer!
}
Edit: As it's been pointed out, the question doesn't make much sense (obviously if you want to implement a feature, you test for it, if you want to detect for a specific browser, you check the user agent), sorry, it's 5am ;) Let me me phrase it like this: Are there any javascript objects and/or features that are unique to Chrome...
isChrome = function() {
return Boolean(window.chrome);
}
This answer is very outdated, but it was very relevant back then in the stone age.
I think feature detect is more usefull than navigator.userAgent parsing, as I googled Opera ambiguosity here. Nobody can know if IE16 will parse the /MSIE 16.0;/ regexp - but we can be quite sure, there will be the document.all support. In real life, the features are usually synonyms for the browsers, like: "No XMLHttpRequest? It is the f....d IE6!"
No nonIE browser supports document.all, but some browsers like Maxthon can scramble the userAgent. (Of course script can define document.all in Firefox for some reason, but it is easilly controllable.) Therefore I suggest this solution.
Edit Here I found complete resources.
Edit 2 I have tested that document.all is also supported by Opera!
var is = {
ff: window.globalStorage,
ie: document.all && !window.opera,
ie6: !window.XMLHttpRequest,
ie7: document.all && window.XMLHttpRequest && !XDomainRequest && !window.opera,
ie8: document.documentMode==8,
opera: Boolean(window.opera),
chrome: Boolean(window.chrome),
safari: window.getComputedStyle && !window.globalStorage && !window.opera
}
Using is simple:
if(is.ie6) { ... }
Not exactly an answer to the question... but if you are trying to detect a specific browser brand, the point of feature-checking is kind of lost. I highly doubt any other browsers are using the Chrome userAgent string, so if your question is 'is this browser Chrome', you should just look at that. (By the way, window.ActiveXObject does not guarantee IE, there are plug-ins for other browsers that provide this object. Which kind of illustrates the point I was trying to make.)
For all the standards nazis... sometimes you might want to use bleeding "standard technologies" which aren't just yet standard but they will be... Such as css3 features.
Which is the reason why I found this page.
For some reason, Safari runs a combo of border-radius with box-shadow just fine, but chrome doesn't render the combination correctly. So it would be nice to find a way to detect chrome even though it is webkit to disable the combination.
I've ran into hundreds of reasons to detect a specific browser/version which usually ends up in scrapping an idea for a cool feature because what I want to do is not supported by the big evil...
But sometimes, some features are just too cool to not use them, even if they aren't standardized yet.
So, if you accept Marijn's point and are interested in testing the user agent string via javascript:
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
(Credit to: http://davidwalsh.name/detecting-google-chrome-javascript )
Here's a really nice analysis/breakdown of the chromes user agent string: http://www.simonwhatley.co.uk/whats-in-google-chromes-user-agent-string
I often use behavior/capability detection. Directly check whether the browser supports functionality before working around it, instead of working around it based on what might be the browser's name (user-agent).
A problem with browser-specific workarounds, is you don't know if the bug has been fixed or if the feature is supported now. When you do capability detection, you know the browser does or doesn't support it directly, and you're not just being browser-ist.
http://diveintohtml5.ep.io/everything.html
You shouldn't be detecting Chrome specifically. If anything, you should be detecting WebKit, since as far as page rendering is concerned, Chrome should behave exactly like other WebKit browsers (Safari, Epiphany).
If you need not only to detect WebKit, but also find out exactly what version is being used, see this link: http://trac.webkit.org/wiki/DetectingWebKit
But again, as other people said above, you shouldn't detect browsers, you should detect features. See this ADC article for more on this: http://developer.apple.com/internet/webcontent/objectdetection.html
One reason you might need to know the browser is Chrome is because it 'is' so damn standards compliant. I have already run into problems with old JavaScript code which I thought was standards compliant (by FF or Opera standards - which are pretty good), but Chrome was even more picky. It forced me to rewriting some code, but at times it might be easier to use the if(isChrome) { blah...blah ) trick to get it running. Chrome seems to work very well (I'm for standard compliance), but sometimes you just need to know what the user is running in grave detail.
Also, Chrome is very fast. Problem is, some JavaScript code unintentionally depends on the slowness of other browsers to work properly, ie: page loading, iframe loading, placement of stylesheet links and javascript links in page head, etc. These can cause new problems with when functions are really available to interact with page elements. So for now, you really might need to know...
I use this code to make bookmarks for each browser (or display a message for webkit)
if (window.sidebar) {
// Mozilla Firefox Bookmark
window.sidebar.addPanel(title, url,"");
} else if( window.external ) { // IE Favorite
if(window.ActiveXObject) {
//ie
window.external.AddFavorite( url, title);
} else {
//chrome
alert('Press ctrl+D to bookmark (Command+D for macs) after you click Ok');
}
} else if(window.opera && window.print) {
// Opera
return true; }
else { //safri
alert('Press ctrl+D to bookmark (Command+D for macs) after you click Ok'); }
There might be false positives since opera also has window.chrome object. As a nice solution I use;
var isOpera = !!window.opera || !!window.opr;// Opera 8.0+
var isChrome = !!window.chrome && !isOpera;
This solution almost always works.
However one thing I discovered is that, isChrome returns false in iPad Chrome version 52.0 as window.chrome returns false.
isIE: !!(!window.addEventListener && window.ActiveXObject),
isIE6: typeof document.createElement('DIV').style.maxHeight == "undefined",
isIE7: !!(!window.addEventListener && window.XMLHttpRequest && !document.querySelectorAll),
isIE8: !!(!window.addEventListener && document.querySelectorAll && document.documentMode == 8),
isGecko: navigator.product == 'Gecko',
isOpera: !!window.opera,
isChrome: !!window.chrome,
isWebkit: !!(!window.opera && !navigator.taintEnable && document.evaluate && navigator.product != 'Gecko'),