JavaScript / HTML: Disable Block of Code Only in Opera - javascript

I want to tell Opera to ignore a block of JavaScript code, but I want all other browsers to recognize that code, something like this:
if NOT Opera:
<script type="text/javascript">
// Code
</script>
Or maybe rather:
<script type="text/javascript">
if NOT Opera:
// Code
</script>
Is there a solution? I would be grateful for your help!

This should do the trick :
<script type="text/javascript">
if(navigator.userAgent.indexOf("Opera") < 0 ) {
// Code
}
</script>

Pretty much all you need is to take a look at the window.navigator.userAgent variable. Within it you'll find a string containing information about the browser you are using. I have no access to a version of safari so I can't really test this out for you -
if (window.navigator.userAgent.match('/safari/i')){
// user is using safari
}
References -
window.navigator.userAgent
string.match
Keep in mind that this is not the best way to do browser detection and will not prevent people from using your site with safari - your JavaScript is viewable and editable by all so if you are thinking of this as a security feature you might want to reconsider it.
I would suggest detecting the users browser on the server side (if you are using PHP then you could use $_SERVER['HTTP_USER_AGENT']) and then have the server return different JavaScript files according to the users browser.

Related

CSS target Safari 8 only

While I was doing some optimizations on my web, I ran into some trouble with Safari.
I have some CSS commands, which are broken on Safari 8 (maybe unsupported?), Safari 9 and all other browsers are OK.
I would like to fix the code for safari 8, without breaking and rebuilding my code using different (and much more complicated) structure to achieve the same output.
So:
Is here a way to target !ONLY! safari version 8?
Targeting could be any-
as comment in html, like old comments for "if IE7"
as in CSS somehow (but -webkit targets all webkit browsers, not only safari)
as in javascript/jquery
So, any sugggestions, please?
You could use browser detection and add or not add (depending on the browser) a class to the body (e.g. <body class="is-safari-8">). In your CSS you could set specific rules only applying to .is-safari-8 and its descendants.
The browser detection itself can be done either on the server or client side. While server side is probably preferable I'm assuming you intend to do it client side.
For this you can either use a library (you should find several with a quick google search but it might be overkill since you are looking for just one specific case) or write your own script to check the user agent.
Here is a helpful source that should get you started:
https://developer.mozilla.org/en/docs/Web/API/Navigator
On a sidenote:
The user agent can be faked (but that probably won't be an issue here).
More importantly: you might want to look up https://modernizr.com/. It's a feature detection script. It might allow you to solve your problem in a more flexible way.
There are lots of different ways you can solve the problem. If you want to inject a stylesheet, you may use the code below:
var ua='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A';
var verRe = /Version\/(\d+)/;
var version = ua.match(verRe);
var safari = ua.indexOf("Safari");
if (safari !== -1) {
if (version[1] <= 8) {
addStyleTag("safari8.css");
}
}
function addStyleTag(url) {
var link,head;
head = document.querySelector("head");
link = document.createElement("link");
link.setAttribute("href",url);
link.setAttribute("type","text/css");
link.setAttribute("rel","stylesheet");
head.appendChild(link);
}
If it was my page, I would write the code to degrade gracefully on Safari.

ActiveXObject javascript Events

I want to utilize events from the IE activex object and can't seem to get it to work.
Please see code below and lemme know if any idea's come to mind:
<html>
<head>
<title>Automate IE</title>
<script type="text/javascript" language="javascript">
var ie = new ActiveXObject( "InternetExplorer.Application" );
[...some calls to ie functions...]
</script>
</head>
<body>
This is a test for IE automation.
</body>
Now I want to be able to use events for the 'ie' object as listed here:MSDN IE Events
But can't seem to get it to work...I tried the following solutions (none worked):
Approach 1:
1. eval( "function ie::EventName(){return MyCustomEvent()}" ); - no joy )-:
Approach 2:
2. <script for="ie" event="EventName">some code here</script> - still no joy )-:
This file is saved with the 'HTA' extension - and runs with the MSHTA scripting host
Any advise \ help on how to do this would be much appreciated...thanks!
I've had success with your first method (see here).
From my experience, the parameters of the function definition must exactly match those of the event definition, e.g. for the BeforeNavigate2 event:
function ie::BeforeNavigate2(pDisp, URL, Flags, TargetFrameName, PostData, Headers, Cancel) {
/* do stuff here */
}
Virtually all the Internet Explorer Application events take some parameters, and therefore your eval doesn't work.
(It's probably self-evident, but you have to fill in the actual event name; you cannot call the function whatever you want.)
I would have answered your question sooner but I had two kids in the last three years ;)
I don't think it is possible in an HTA anymore. ActiveXObjects have never supported events in JScript. Before IE11 you could have used VBScript and CreateObject(object, event_prefix) to register event hooks - https://msdn.microsoft.com/en-us/library/xzysf6hc(v=vs.84).aspx (And you only need to register the events in VBScript because the VBScript variables can be accessed in JavaScript.)
If IE<11 is not an option you'll need to use WScript/CScript. Here is a gist for example: https://gist.github.com/subzey/4374329
Executing WScript from an HTA is feasible with the WScript.Shell activex object, but don't get your hopes up because there is no analogous WScript.CreateObject ActiveX object (or anyway to access CreateObject() from JavaScript/JScript.)
To achieve what you want, you'd need to wrap your IE logic up in a WScript/CScript host script that monitors (or polls) a file on your hard drive. Then your HTA application can write commands to that file. If you need a feedback loop your HTA could monitor a command-result file that gets updated when the JScript logic finishes.
I've been a proponent of HTA's since the 90's, and I still use them for personal quick and dirty projects, but the writing is on the wall about their longevity. There are already a bunch of bugs related to the host window since IE10 and Microsoft has confirmed they won't be fixed.
Given that, you might want to investigate Electron as an alternative if you were not relying on IE-specific functionality: http://electron.atom.io/docs/v0.27.0/api/browser-window/

browser identification

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).

Include different JavaScript file depending on browser?

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>

disable javascript on ie browsers

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.

Categories

Resources