comp.lang.javascript FAQ - 7.5 - 2001-11-26

1 meta-FAQ meta-questions

2 comp.lang.javascript tips

2.1 Which newsgroup deals with javascript?
2.2 What questions are off-topic for clj?
2.3 What do I have to do before posting to clj?
2.4 Why was my post not answered?
2.5 How do I direct someone to this FAQ?
2.6 What is ECMAScript?
2.7 What is JScript?
2.8 What are object models?
2.9 What is the document object model?
2.10 Internationalisation in javascript.
2.11 I have a question that is not answered in here or in any of the resources mentioned here but I'm sure it has been answered in clj. Where are the clj archives located?
2.12 What does the future hold for ECMAScript?

3 javascript resources

3.1 What books cover javascript?
3.2 What online resources are available?

4 Quick Answers

4.1 How do I protect my javascript code?
4.2 How can I disable the back button in a web browser?
4.3 How can I access the client-side filesystem?
4.4 How can I see in javascript if a web browser accepts cookies?
4.5 How can I protect a webpage in javascript?
4.6 How do I format 6.57634 to 6.58 or 6.5 to 6.50?
4.7 Why does 5 * 1.015 != 5.075 or 0.05+0.01 != 0.06?
4.8 How do I communicate between frames in a web browser?
4.9 How do I find the size of a browser window?
4.10 How do I check to see if a childwindow is open, before opening another?
4.11 Why does framename.print() not print the right frame in IE?
4.12 Why does parseInt(09) give an error?
4.13 How do I get the value of a SELECT box in NN?
4.14 How do I close a window and why does it not work on the first one?
4.15 How do I modify the current page in a browser?
4.16 How do I trim whitespace - LTRIM/RTRIM/TRIM?
4.17 How do I force a reload from the server/prevent caching?
4.18 How do I get a perl/asp/php variable into client-side js?
4.19 Why do I get permission denied when accessing a frame?
4.20 How do I make a 10 second delay?
4.21 Why does 1+1 equal 11?
4.22 How do I generate a random integer in [1..N]?
4.23 How do I change print settings with window.print()?
4.24 I have <a href="javascript:somefunction()"> what ... ?
4.25 My element is named myselect[] , how do I access it?
4.26 How do I detect Opera/Netscape/IE?
4.27 How do I disable the right mouse button?

5 Comments

1 meta-FAQ meta-questions

You are reading the comp.lang.javascript meta-FAQ, version 7.5

This is the official comp.lang.javascript (clj) FAQ. Or, more accurately, the meta-FAQ as it mainly provides URLs to further information about javascript and some hints and tips to make your stay in comp.lang.javascript more enjoyable.

This document was created to help reduce the high levels of noise on clj and to provide a resource for people new to javascript or who want to know locations of valuable javascript resources.

The FAQ will currently be posted in two parts, one part (the Quick Answers) on Mondays and Fridays, with the remainder posted on wednesdays

It is also available on the web at http://www.jibbering.com/faq/

Conventions used in the HTML version.

If your browser supports CSS, and follows our Suggestions, we use these conventions to denote various things:

Pages linked to from within a blue dashed line were updated since the last publication of the comp.lang.javascript FAQ (2001-11-26). Links contained in a red dotted line were unavailable at the time of publication.

Boxes with a light blue background, contain links to more information on the question discussed. Code samples are given in a yellow background.

2 comp.lang.javascript tips

2.1 Which newsgroup deals with javascript?

comp.lang.javascript is the official Usenet newsgroup dealing with javascript. There are other newsgroups but many of them are not carried by most news feeds. clj is an unmoderated newsgroup.

2.2 What questions are off-topic for clj?

clj deals with ECMAScript languages, so any questions about JavaScript or JScript are welcome - however the group has a majority of questions about using javascript in a browser, please make it obvious which host you are using javascript in.

Javascript and Java are two completely different languages. Java questions should be asked in one of the comp.lang.java.* newsgroups; they are not appropriate for clj.

Questions dealing with other scripting languages, such as VBScript, PerlScript or CGI scripting are also off-topic, as are HTML-only or CSS-only questions.

2.3 What do I have to do before posting to clj?

Before posting to clj, you should thoroughly read this document. You should also check the resources mentioned in section 3 and the Quick Answers in section 4. Read FYI28/RFC1855 http://www.ietf.org/rfc/rfc1855.txt , on Usenet and/or http://www.jsiinc.com/newsgroup_document.htm . Also you should read all appropriate posts to the clj newsgroup for several days. Most questions come up at least once every other day and people can get annoyed of answering them repeatedly.

Please state your question as clearly and concisely as possible, as this will make it far easier for the other readers of the list to understand your problems and suggest possible solutions. Use the Subject: of your post to indicate the type of problem you have. 'Help!' or 'I hate Netscape!' are not nearly as useful to contributors who do not read every post as 'parseInt(09)!=9'.

Has the same question already been posted that day? - if it has wait to see if the answers to that solve your problem.

Include the script you have been working on (or URL) - indicate the problem spots and/or previous attempts. Try to limit the length of your post by removing extraneous page elements, but avoid removing script unless you are sure it is not an issue. If the script is long though, please do not post the full script and just provide a link, as a guide more than 500 lines for a post is not normally a good idea in any circumstances. A mention of which platforms and browsers in use or giving problems is also necessary.

Post in plain-text only. Do not post using HTML. If you have to include your script, paste it in to your post in plain-text, do not uuencode it or attach it using mime. There is good reason for this request. Many newsreaders do not read html or mime, and this limits the number of people who could help you. Before a reply, quote only the minimum that needs to be quoted, and add your comments below the quoted material, as FYI28/RFC1855.

Don't ask, or at least expect, to be emailed individually. Some individuals run scams for the purpose of collecting active email addresses and many won't risk being victimized. If you have circumstances that won't allow you to read clj for the follow-up, explain what they are and ask to be CC'ed a copy. You also might try http://groups.google.com/ to read replies.

Don't take flames too seriously. And don't start a thread complaining about rude or flippant responses, there is already enough noise in clj. Keep a sense of humour while posting and reading and everything will be a lot more enjoyable.

Remember that it is not the job of posters here to help you, that the majority of regular posters here do so voluntarily in their free time. They have good days and bad days just like everyone else.

clj is a technical group, postings of job adverts and commercial adverts are not welcome - job postings should go to an appropriate regional jobs group. Announcements of products of particular relevance to javascript are welcome, but not more often than once per major release - then post a short link to your products webpage.

2.4 Why was my post not answered?

This could be for several reasons:

If it's not one of these, then after a few days consider reposting after checking http://groups.google.com/ for replies. Make sure the post is phrased well, and everything needed to answer is correct, and the subject is appropriate.

2.5 How do I direct someone to this FAQ?

This document is posted to clj very frequently. There should be no reason to direct someone to it. However, if someone asks a question answered in this FAQ or in one of the resources listed herein, please let them know their question is answered in the FAQ and that the FAQ can be found at http://www.jibbering.com/faq/

2.6 What is ECMAScript?

http://www.ecma.ch/ecma1/STAND/ECMA-262.HTM ECMAScript is the international standard for javascript. JScript 3.0 and JavaScript 1.2 (available with version 4. browsers) are more or less ECMAScript compliant. Note that ECMAScript did not attempt to standardize the document object model.

The current edition is Edition 3.0, There is some support for this edition in JScript 5.0 and JavaScript 1.3, JScript 5.5 is compliant, and JavaScript 1.5 available in Netscape 6.1 and later is compliant (Netscape 6 JavaScript 1.5 missed some methods.)

2.7 What is JScript?

JScript is Microsoft's implementation of ECMAScript.

2.8 What are object models?

Object models (OMs) are not part of the javascript language, they are provided by the host to allow javascript (or other scripting language) to communicate with the host. An object model may allow a javascript to access a file system, or control a nuclear power station. The most commonly used object models via javascript are provided by Active Server Pages, Server Side JavaScript, and the Windows Script Host. The most common of all of course is the Document Object Model (DOM) provided by web browsers.

2.9 What is the document object model?

This is the collection of objects provided by each browser. Basically, any object in the window hierarchy is part of the DOM. This means that document.writeln(), for example, is not a javascript method but is, in fact, a method provided by the DOM. The DOM has been standardised by the w3 consortium; however, like all w3 standards, browser support unfortunately is not there yet. Most cross-browser coding problems come from slightly different implementations of the DOM in the different browsers. W3 DOM FAQ http://www.w3.org/DOM/faq

2.10 Internationalisation in javascript.

There is little Internationalisation capability in javascript, the various toString() methods are all implementation dependant, but tend to use UK/US settings. ECMAScript Edition 3.0 has introduced some capability including the toLocaleString() method which should create a string based on the hosts locale. In future versions of javascript it is expected that there will be much more support based on the host's Locale.

2.11 I have a question that is not answered in here or in any of the resources mentioned here but I'm sure it has been answered in clj. Where are the clj archives located?

http://groups.google.com/ Maintain a usenet archive going back over 5 years.

2.12 What does the future hold for ECMAScript?

The ECMAScript Technical commitee is now working on Edition 4, the first implementation of which is likely to be JScript.NET, which is currently available in beta form - it includes a compiler, allowing you to create standalone JScript executables.

Edition 4.0 of ECMAScript provides new features like typed variables, classes, other information can be found at: http://www.mozilla.org/js/language/es4/index.html , http://msdn.microsoft.com/voices/scripting07142000.asp or from microsoft.public.dotnet.languages.jscript

3 javascript resources

3.1 What books cover javascript?

There are rather a lot of javascript books available, and if anyone has an example of an up to date good javascript book, I'll gladly add it to the faq.

3.2 What online resources are available?

Javascript FAQ sites, please check these first:
http://www.irt.org/script/faq.htm
http://javascript.faqts.com/
Index of docs online and for download:
http://docs.iplanet.com/docs/manuals/javascript.html
Microsoft (D)HTML reference:
http://msdn.microsoft.com/workshop/author/dhtml/reference/dhtmlrefs.asp
or anonymous FTP of these 2 files:
ftp://ftp.microsoft.com/developr/platformsdk/feb2001/common/help/inet.chm
ftp://ftp.microsoft.com/developr/platformsdk/feb2001/common/help/inet.chi
JScript reference and main Microsoft script site:
http://msdn.microsoft.com/library/en-us/script56/html/js56jsoriJScript.asp
http://msdn.microsoft.com/scripting/
Opera Documentation
http://www.opera.com/docs/specs/#ecmascript
http://www.opera.com/docs/specs/js/
ICab's Inscript documentation
http://www.muchsoft.com/inscript/
Archived documentation for MSIE 3.x:
http://members.tripod.com/~housten/download/
The official ECMAScript specification:
http://www.ecma.ch/ecma1/STAND/ECMA-262.HTM
DOM level 1 ECMA script binding:
http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
FESI - a free implementation of ECMAScript in Java:
http://home.worldcom.ch/~jmlugrin/fesi/index.html
Frequently asked questions about source code obfuscation:
http://ugweb.cs.ualberta.ca/~thompson/programming/javascript/protect.html
Sites discussing Active Server Pages:
http://www.15seconds.com/
http://www.4guysfromrolla.com/
http://www.aspfaq.com/
DHTML source code and tutorials to a high standard:
http://www.dansteinman.com/dynduo/
http://www.w3schools.com/
Sites focused on using Scripting to automate Windows:
http://www.windows-script.com/
http://cwashington.netreach.net/
Code for manipulating times and dates in javascript:
http://www.merlyn.demon.co.uk/js-dates.htm
Games written in javascript:
http://www.javascript-games.org/
Venkman - Mozilla Visual JS debugger
http://www.mozilla.org/projects/venkman/
Whitebeam Apache Module - Server Side Javascript in Apache
http://www.whitebeam.org/

4 Quick Answers

4.1 How do I protect my javascript code?

In the main you don't, as the language is ran from source, you need to deliver the source code, with JScript, there is the Script Encoder (see MSDN) but this is nothing more than obfuscation in effect, disabling the Right Mouse button, also achieves nothing to protect your script in a web browser.

Your code is likely protected under copyright laws. See:
http://www.wipo.org/about-ip/en/copyright.html
http://html.about.com/compute/html/msubcopyright.htm

4.2 How can I disable the back button in a web browser?

You can't. The browser's history cannot be modified. You can however use location.replace(url) in some browsers to replace the current page in the history.

http://msdn.microsoft.com/workshop/author/dhtml/reference/methods/replace.asp
http://developer.netscape.com/docs/manuals/js/client/jsref/location.htm#1194240

4.3 How can I access the client-side filesystem?

Security means that by default you can't. In a more restricted enviroment, there are options (e.g. live connect to Java in NN, and using FileSystemObject in IE) check http://groups.google.com/ for previous posts on the subject.

http://msdn.microsoft.com/library/en-us/script56/html/jsobjFileSystem.asp
http://www.javaworld.com/javaworld/jw-10-1998/jw-10-apptowin32.html

4.4 How can I see in javascript if a web browser accepts cookies?

Writing a cookie, reading it back and checking if it's the same.

http://tech.irt.org/articles/js064/index.htm

4.5 How can I protect a webpage in javascript?

In practice you can't, Whilst you could create a suitable encryption system with a password in the page, the level of support you need to do this means it's always simpler to do it serverside. Anything that "protects" a page other than the current one is definitely flawed

4.6 How do I format 6.57634 to 6.58 or 6.5 to 6.50?

In ECMAScript Ed. 3.0 (JScript 5.5 (but buggy)/JavaScript 1.5) num.toFixed(2) or for previous versions Math.round(num*100)/100 , (doesn't add trailing zeros.)

Adding trailing zeros is more complicated to achieve without failing for some numbers. The below works successfully:

 function Stretch(Q, L, c) { var S = Q
 if (c.length>0) while (S.length<L) { S = c+S }
 return S
}
 function StrU(X, M, N) { // X>=0.0
 var T, S=new String(Math.round(X*Number("1e"+N)))
 if (S.search && S.search(/\D/)!=-1) { return ''+X }
 with (new String(Stretch(S, M+N, '0')))
 return substring(0, T=(length-N)) + '.' + substring(T)
}
 function Sign(X) { return X<0 ? '-' : ''; }
function StrS(X, M, N) { return Sign(X)+StrU(Math.abs(X), M, N) }
 Number.prototype.toFixed= new Function('n','return StrS(this,1,n)')
http://www.merlyn.demon.co.uk/js-round.htm
http://msdn.microsoft.com/library/en-us/script56/html/js56jsmthToFixed.asp

4.7 Why does 5 * 1.015 != 5.075 or 0.05+0.01 != 0.06?

Javascript numbers are represented in binary as IEEE-754 Doubles, with a resolution of 53 bits, giving an accuracy of 15-16 decimal digits; integers up to about 9e15 are precise, but few decimal fractions are. Given this, arithmetic is as exact as possible, but no more. Operations on integers are exact if the true result and all intermediates are integers within that range.

In particular, non-integer results should not normally be compared for equality; and non-integer computed results generally need rounding; see 4.6.

http://msdn.microsoft.com/library/en-us/script56/html/js56jscondatatype.asp

4.8 How do I communicate between frames in a web browser?

To reference another frame, you simply need to step through the frame hierarchy, parent is the page the frame is defined in, parent.framename is another frame in the same frameset as the frame you are in. So to access a variable called Moomin in a frame called Snork that is in the same frameset you're in you would use parent.Snork.Moomin , to call the function Snufkin in that frame you would use parent.Snork.Snufkin() .

4.9 How do I find the size of a browser window?

Where supported in NN: (>NN4.0)

 var winWidth = window.innerWidth;
var winHeight = window.innerHeight;      

Where supported in IE: (>IE4.0)

 var winWidth = document.body.clientWidth;
var winHeight = document.body.clientHeight;      

When using IE6 with a DOCTYPE:

 var winWidth = document.documentElement.clientWidth
var winHeight = document.documentElement.clientHeight      

Combined:

 d=document
if (typeof window.innerWidth!='undefined') {
 var winWidth = window.innerWidth;
 var winHeight = window.innerHeight;
} else {
 if (d.documentElement && 
  typeof d.documentElement.clientWidth!='undefined' && 
   d.documentElement.clientWidth!=0) {
  var winWidth = d.documentElement.clientWidth
  var winHeight = d.documentElement.clientHeight
 } else {
  if (d.body && 
   typeof d.body.clientWidth!='undefined') {
   var winWidth = d.body.clientWidth
   var winHeight = d.body.clientHeight
  }
 }
}      
http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/clientWidth.asp
http://developer.netscape.com/docs/manuals/js/client/jsref/window.htm#1202446
http://msdn.microsoft.com/workshop/author/om/measuring.asp

4.10 How do I check to see if a childwindow is open, before opening another?

 var myWin=null;
function openWin(aURL) {
 if (!myWin || myWin.closed ) {
  myWin=window.open(aURL,'myWin');
 } else{
  myWin.location=aURL;
  myWin.focus();
 }
}      
http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/closed.asp
http://developer.netscape.com/docs/manuals/js/client/jsref/window.htm#1201877

4.11 Why does framename.print() not print the right frame in IE?

IE prints the frame that has focus when you call the print method frameref.focus();frameref.print();

http://msdn.microsoft.com/library/en-us/dnscrpt/html/dhtmlprint.asp

4.12 Why does parseInt(09) give an error?

parseInt decides what base the number is by looking at the number. By convention it assumes any number beginning with 0 is Octal, and any number beginning with 0x Hexadecimal. To force use of base 10 add a second parameter parseInt(09,10)

http://msdn.microsoft.com/library/en-us/script56/html/js56jsmthparseint.asp
http://developer.netscape.com/docs/manuals/js/client/jsref/toplev.htm#1064173

4.13 How do I get the value of a SELECT box in NN?

 el=document.forms['formname'].elements['elementname'];
value=el.options[el.selectedIndex].value;      
http://developer.netscape.com/docs/manuals/js/client/jsref/select.htm

4.14 How do I close a window and why does it not work on the first one?

The script windowref.close(); windowref is window, or self, top, parent, or a reference obtained when opening the window, you can only close windows opened by script, no others.

http://msdn.microsoft.com/workshop/author/dhtml/reference/methods/close_0.asp
http://developer.netscape.com/docs/manuals/js/client/jsref/window.htm#1201822

4.15 How do I modify the current page in a browser?

At its simplest in current DOM2 (with innerHTML extension) (IE5+ NS6 ) then having HTML of <div id="aID">Some Content</div> with script of document.getElementById("aID").innerHTML="Some <em>new</em> Content"; works.

It is possible though in IE 4+, NS 4+. Code like below achieves it, but not without many problems in more complicated situations than described. Be careful - HTML: <div ID=aID><layer name='NS_aID';>Some Content</layer></div> and script DynWrite('aID',"Some <em>new</em> Content") With the below code also in the page:

 DocDom = (document.getElementById?true:false);
DocLay = (document.layers?true:false);
DocAll = (document.all?true:false);
DocStr=''
if (DocLay) DocStr="return document.layers['NS_'+id]"
if (DocAll) DocStr="return document.all[id]"
if (DocDom) DocStr="return document.getElementById(id)"
GetRef=new Function("id", DocStr)
if (DocStr=='') { DynWrite=new Function("return false") } else {
 if (DocAll || DocDom) {
  DynWrite=new Function("id", "S", "GetRef(id).innerHTML=S; return true")
 }
if (DocLay) DynWrite=new Function("id", "S", "var x=GetRef(id).document;"+
 "x.open('text/html'); x.write(S); x.close(); return true")
}      
http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/innerHTML.asp
http://www.mozilla.org/docs/dom/domref/dom_el_ref8.html#1018427

4.16 How do I trim whitespace - LTRIM/RTRIM/TRIM?

Using Regular Expressions (JavaScript 1.2/JScript 4+) :

 String.prototype.LTrim=new Function("return this.replace(/^\\s+/,'')")
String.prototype.RTrim=new Function("return this.replace(/\\s+$/,'')")
String.prototype.Trim=
                 new Function("return this.replace(/^\\s+|\\s+$/,'')")

or for all versions (trims characters ASCII<32 not true "whitespace"):

 function LTrim(str) {
 for (var i=0; str.charAt(i)<=" "; i++);
 return str.substring(i,str.length);
}
function RTrim(str) {
 for (var i=str.length-1; str.charAt(i)<=" "; i--);
 return str.substring(0,i+1);
}
function Trim(str) {
 return LTrim(RTrim(str));
}      
http://msdn.microsoft.com/library/en-us/script56/html/js56reconIntroductionToRegularExpressions.asp
http://developer.netscape.com/docs/manuals/js/client/jsref/regexp.htm

4.17 How do I force a reload from the server/prevent caching?

To reload a page, location.reload() works, however this does depend on the cache headers that your server sends, to change this you need to change your server - a quick fix to this on the client side is to change the URI of the page so it contains a unique element such as the current date. location.replace(location.href+'?d='+new Date().valueOf()) of if the location.href already contains a Query String location.replace(location.href+'&d='+new Date().valueOf())

http://www.mnot.net/cache_docs/
http://developer.netscape.com/docs/manuals/js/client/jsref/date.htm

4.18 How do I get a perl/asp/php variable into client-side js?

You have the serverside language generate the javascript:

 jsvar="<%= aspvar %>";
jsvar="<?php echo $phpvar ?>";      

etc. For communication between client and server, after a page has loaded, there are a number of "Remote Scripting" options available:

http://www.ashleyit.com/rs/main.htm

4.19 Why do I get permission denied when accessing a frame?

In the normal browser security it is impossible for a script from one domain to access properties of pages served from another domain or by a different protocol, and any attempt by your script to access a property of a window in a different domain will result in a permission denied error. Signed scripts, or trusted ActiveX's can overcome this in limited situations.

http://msdn.microsoft.com/workshop/author/om/xframe_scripting_security.asp

4.20 How do I make a 10 second delay?

There is no ability to cause a delay in javascript, host Object Models usually provide something. In the browser, there is window.setTimeout which can be used to create a delay.

To call the function Snork() , approx 10 seconds after the function Moomin() , you would do this:

 Moomin()
setTimeout('Snork()',10000)      

Script execution is not stopped, and adding Snufkin() after the setTimeout line would immediately execute the function Snufkin() before Snork()

Other hosts have different wait functions such as Windows Script Hosts WScript.Sleep()

http://msdn.microsoft.com/workshop/author/dhtml/reference/methods/setTimeout.asp
http://developer.netscape.com/docs/manuals/js/client/jsref/window.htm#1203758

4.21 Why does 1+1 equal 11?

Javascript variables are loosely typed, and conversion between Strings and Numbers happen freely, since + is also used for String concatenation, "1"+1 is equal to 11 - the String deciding what + does, to overcome this convert the String to a number: Number("1") or "1"*1 or "1"-0 or parseInt("1") or parseFloat("1") or +varname . Prompt and Form element values are all Strings, so convert them to numbers before performing addition.

http://msdn.microsoft.com/library/en-us/script56/html/js56jscondeclare.asp

4.22 How do I generate a random integer in [1..N]?

 function Random(x) { return Math.floor(x*Math.random()) }

gives a random number between 0..(x-1); Random(N)+1 for [1..N]

http://msdn.microsoft.com/library/en-us/script56/html/js56jsmthrandom.asp
http://developer.netscape.com/docs/manuals/js/client/jsref/math.htm#1197697

4.23 How do I change print settings with window.print()?

In a normal security enviroment, you can't change anything. The page stylesheet rules provide some options, but are not supported in browsers yet. If you can, use an ActiveX or Plugin ScriptX and Neptune from Meadroid to give you more control for Windows versions of Internet Explorer and Netscape 4,6 and Opera 5.

http://www.meadroid.com/scriptx/
http://msdn.microsoft.com/library/en-us/dnscrpt/html/dhtmlprint.asp

4.24 I have <a href="javascript:somefunction()"> what ... ?

Whatever the rest of your question, this is generally a very bad use of the javascript pseudo protocol. It was designed to be a method that a javascript function could return the new page e.g. javascript:return "<p>Hello</p>" To use it simply to call a function, which you then return false from, causes user agents which do not understand javascript, or have it disabled, to get nothing other than an error. <a href="something.html" onclick="somefunction();return false"> where something.html is meaningful to the non-javascript capable, is nearly always preferable. Or use onclick on another element so users without javascript aren't even led to believe it does anything.

4.25 My element is named myselect[] , how do I access it?

Form elements with any "illegal" characters can be accessed with formref.elements["myselect[]"] - These characters are illegal in the standard (x)HTML doctypes, so you should try to avoid them as browsers may perform incorrectly though.

http://msdn.microsoft.com/workshop/author/dhtml/reference/collections/elements.asp
http://developer.netscape.com/docs/manuals/js/client/jsref/form.htm#1193375
http://jscript.dk/faq/php.asp

4.26 How do I detect Opera/Netscape/IE?

The navigator object contains strings which specify the browser and version; however, this is in general not very genuine. Mozilla (and therefore Netscape 6) allows this to be freely set, and Opera and IE allow it to be modified. There are also at least 25 other javascript capable browsers with their own strings here.

Generally though, you don't need to identify which browser is being used. There are alternative techniques which depend on why you want to redirect browsers - if it's to offer different CSS stylesheets, then http://pixels.pixelpark.com/~koch/hide_css_from_browsers/ shows many techniques. For Scripting, Object or Feature detection is a better method to use.

Object Detection means checking that the object you wish to use is supported by the browser before using it. This means that you don't need to know what browsers support what methods, and your code will automatically be usable on any browser that can execute it.

 if (document.getElementById &&
  document.getElementById('el') &&
    document.getElementById('el').style ) {
  // We know that this browser supports getElementByID and has
  // a style object, so we can set a style property.
  document.getElementById('el').style.color="red";
}      

Browser bugs can often be detected and overcome in similar ways.

4.27 How do I disable the right mouse button?

The event oncontextmenu of HTML attributes in IE and Mozilla, is the only reliable and safe method of blocking the context menu, the other approaches often presented, rarely work, and rely on alert boxes coming up and even then are limited in their scope: <body oncontextmenu="return false">

5 Comments

If you have any suggestions for the FAQ, or further questions that you feel should be answered here, please e-mail me at jim@jibbering.com .

The FAQ uses the stylesheet faq.css and is generated from the xml source index.xml by the windows script host script process.wsf which also checks the links.