You've heard of a FAQ -- typically a list of frequently asked questions on some topic or another. A twist on that idea, FSS -- for frequently sought solutions, is a list of the most common pleas made by programmers. The topics addressed tend to go beyond "newbie" questions and address real-life problems encountered when creating a working program.
In my ten-plus months of working with JavaScript, I've encountered about a dozen topics common to most JavaScript programmers. These include how to best work with different versions of Netscape, how to ensure compatibility with Microsoft Internet Explorer, and how to access variables and forms in another frame. This month we'll discuss all this and more.
First, what JavaScript can't do
There are a number of frequently sought solutions that JavaScript can't provide, either because the language is not powerful enough to support it or because it is specifically designed to disallow it (most likely for security or privacy reasons).
How do I use JavaScript to password protect a page?
Only a server can provide true password protection for documents. The typical user authentication used by Unix and NT servers allows a Webmaster to lock out files and/or directories, requiring a login name and password for access. If an invalid login name or password is provided, the server refuses access.
In the realm of JavaScript used in an HTML page and interpreted by Navigator or Internet Explorer, there is no sure way to restrict access to a server page, though there is a way to help "hide" a URL to an existing page, and therefore keep out the casual user. You can hard-code a matching password in your JavaScript program, but a slightly more secure method is to use a cipher of some type so that the unlocking password itself is not readily visible in the View Source window. I have an example of how to do this at my JavaScript home page, so I won't repeat it here. The URL is: http://gmccomb.com/javascript/password_doc.html
How do I read and write disk files with JavaScript?
JavaScript is specifically disallowed from any kind of input/output because of security concerns. (Actually, that's not quite true. JavaScript can use the cookies function of Netscape to store persistent data. However, it is Netscape that controls the reading and writing of this file, not JavaScript.)
Because JavaScript has no input or output stream capabilities, it is not possible to use it to read a flat-file database or to format a text document and save it to disk. JavaScript is limited to reading and writing the content of standard HTML forms, which can be passed between client and browser if there is a need to exchange data. If you'd like to use JavaScript to write to a file, you must take the long route: fill out a form, use JavaScript to help mail the form, then receive the form via standard e-mail.
How do I use JavaScript to read e-mail names of visitors to my Web page?
The initial release of Netscape 2.0 allowed Webmasters to secretly capture e-mail names of anyone who visited their sites. This was done by including a form in the page along with a JavaScript submit() instruction for sending the form. The form was covertly mailed to the Webmaster using an ACTION attribute set to something like mailto:name@server.com.
This bug was quickly recognized, and since Netscape 2.01 this feature has been disabled or restricted. In Netscape 2.01 and 2.02, JavaScript ignores the combination of submit() and mailto:. In Netscape 3.0, it is now possible to work around this restriction using the click() method. However, it's important to remember that the default setting of Netscape warns users that their e-mail names are about to be sent. They can choose to cancel the submission.
How do I prevent others from viewing my JavaScript code?
Programmers are justifiably nervous about spending days, weeks, or even months on a project, only to have the code for it openly available and therefore "free for the taking" by anyone. JavaScript is both an interpreted language and a client-based language, which means that the code for a JavaScript program is readily viewable by anyone who knows how to use the View Source command, or save a page to a local disk file.
Since there is no way to prevent others from viewing (and possibly stealing) your work, you have two alternatives:
- Forget about it, and get on with the next project.
- Rewrite the code using Java, or a server-side program.
How do I make sure my program works on every version of Navigator and Internet Explorer?
This question is placed in the "what JavaScript cannot do" section because writing universal JavaScript code -- at least code of any complexity -- is not possible, even for Netscape.
The JavaScript language specification has been too fluid to assure compatibility across versions. Bugs, quirks, and glitches exist from version to version, making it extremely difficult to ensure that pages work reliably for everyone. As an example, certain aspects of using the document.write() method with frames were "broken" in Netscape 2.01 for some platforms. The problem was fixed for users of 2.02 and 3.0, but there are still copies of 2.01 in use.
Compounding the problem, JavaScript can behave differently from platform to platform. This is to be expected to some degree, but the problem ranges from mere annoyances to downright hair-pulling grief. As an example, in Netscape 2.0x the document.title property cannot be read when using a Unix version of Netscape. In other versions the property returns the title of the document as it should.
If you must make your pages 100% compatible with all versions of Netscape Navigator 2.0x and 3.0, and possibly even with Internet Explorer 3.0 as well, you're best off limiting the JavaScript code you use. More elaborate scripts, such as those that interact with other windows or frames, are more prone to give you compatibility problems.
How do I use the new JavaScript 1.1 commands in Internet Explorer 3.0?
Easy answer: you don't. JavaScript 1.1 (the new version of JavaScript as used in Navigator 3.0) offers functionality that Internet Explorer 3.0 does not yet currently support.
The 10 most common solutions JavaScript programmers ask for
Here are ten of the most commonly asked-for solutions by those working with JavaScript. Where appropriate, a short example is provided for each problem/solution.
1. How to change the URL of a window or frame
Use the location object, as shown:
location = URL;
URL
is the URL you want to use, such as:
location = "index.html"
If you'd like to change the URL of a frame, provide the full object hierarchy to the frame, as in:
parent.framename.location = URL;
framename
is the name of the frame you want to use, and URL
is the fully qualified URL you want to point to. Example:
parent.frame_a.location = "http://mydomain.com/javascript/index.html"
Note that I've provided an absolute URL, rather than a relative one. While this is considered optional, it's good practice because some versions of JavaScript may fail to update the frame unless the URL is absolute.
2. How to play a sound
In Navigator 2.0x and 3.0, you can automatically play a sound using the location
object. Merely specify the URL to the sound file, as in:
location = meow.au;
If you are designing Web pages for Navigator 3.0, you may be better off using the sound-player plug-in, which you specify in HTML using the <EMBED> tag. If you are designing solely for Internet Explorer, you can use the <BGSOUND> tag instead, which can play a sound file once or repeatedly.
3. Referencing one frame from another frame
You may use JavaScript to reference one frame from another frame. You can use this technique to pass values between frames in a window, for example, or to manipulate the content in another frame. One typical example of this is to write new content to a frame. "Frame A" contains the JavaScript code that controls the writing, and "Frame B" is the blank frame that will be written to. To reference the other frame you provide its full object hierarchy, starting with the parent window object. Frames are siblings of the parent, so the reference to a given frame (assuming non-nested frames) is:
parent.framename
where framename
is any valid frame name. As an extended example, to read the content of a text box within a form in another frame, you'd first reference the frame, then reference the form within that frame.
parent.framename.document.formname.controlname.value;
framename
is the name of the frameformname
is the name of the form that contains the text box you want to usecontrolname
is the unique name for the text box in the form.
4. Writing new JavaScript code to a frame
Extending the above example, you can use frames and JavaScript to create even more JavaScript. You use the document.write method to insert the JavaScript code of your choice into a new window or a frame (you must do this from another window or frame otherwise, writing the next script will overwrite the old script).
However, if you try this you'll find that JavaScript invokes an error when it encounters a document.write instruction with the word </SCRIPT> in it. The reason: JavaScript sees the </SCRIPT> tag in the document.write instruction, and assumes it means its own script is over.
Fortunately, there's an easy work-around: just add a backslash character before the </SCRIPT> tag, as in \ /SCRIPT. This forces JavaScript to not treat the </SCRIPT> tag in the document.write instruction as a terminator for its own script. Example:
patrent.framea.document.write ("<SCRIPT>alert ('hello') <\/SCRIPT>");
5. Stop the form from being submitted when pressing the Enter key
Netscape Navigator and most other browsers are designed to automatically submit a form when the user presses the Enter key when using a form with just one text box. This can be a useful feature; for example, it can save the user from having to click on a separate "Submit" button.
But there are times when you specifically want to avoid submitting a form when the user presses Enter. This is done with the onSubmit
event, placed in the <FORM> tag, as shown here.
<FORM NAME="myform" onSubmit="return false;" > Please type your name, and click OK<BR> <INPUT TYPE="text" NAME="key1" VALUE = "hello there"> <P> <INPUT TYPE="button" NAME="button" VALUE="OK" onClick="submitNow(this.form)" ><P> </FORM>
The form (named "myform") includes the onSubmit
event handler in the <FORM> tag. The handler specifies that when a submit event occurs, JavaScript should return a value of false, thereby stopping the submission. The onSubmit
event handler takes care of submitting the form when the user presses the Enter key after typing text in the text box.
You will likely still want a means to submit the form (when the user is ready), which can be handled by a button. The button uses an onClick
event handler to call a function named submitNow
. The current form object is passed to this function as this.form. The submitNow
function is relatively simple. But do note that this only works if you are not using a mailto URL for the ACTION attribute of the <FORM> tag.
function submitNow(form) { form.submit(); }
Notice that the submit
method is used with the form
object, passed to the submitNow
function. This ensures that the proper form is submitted, should you have more than one form in the document. Here's a more complete working example, showing two forms in the document. The first form submits when you press the Enter key while in the top text box. The second form disallows the Enter key from submitting the form. Instead, you must click the OK button.
<HTML> <HEAD> <SCRIPT LANGUAGE="JavaScript"> function submitNow(form) { form.submit(); } </SCRIPT> </HEAD> <BODY> <FORM NAME="form1"> Please type your name ane click OK<BR> <INPUT TYPE="text" NAME="myname"><P> </FORM> <P> <FORM NAME="form2" onSubmit="return false;" > Please type your address and click OK<BR> <INPUT TYPE="text" NAME="myaddress"><P> <INPUT TYPE="button" NAME="button" VALUE="OK" onClick="submitNow(this.form)" ><P> </FORM> </BODY> </HTML>
6. Mail a form using JavaScript
Netscape lets you mail the contents of form fields to yourself or any other valid e-mail address. You can use this feature to process a form, without having to invest time and energy (and maybe money) in a "formmail" CGI program that runs on a server. There are limitations regarding the mailing of forms with JavaScript, however. (See the section above on the use of mailto: and the submit() method to "silently" send a form.) Depending on what you want to do, you may be thrilled or disappointed by what Netscape and JavaScript offer.
The basic HTML syntax for mailing a form is quite simple and does not require JavaScript. You merely add the mailto: protocol, along with the e-mail address, as the ACTION attribute of the <FORM> tag. It looks like this:
<FORM ACTION="mailto:jowbloe@domain.com" METHOD=post>
Following this tag are one or more form object tags, such as text boxes or radio buttons. You also provide a submit button tag to submit the form. Here's a working form with one text field and a submit button:
<FORM ACTION="mailto:jowbloe@domain.com" METHOD=post> <INPUT TYPE="text" NAME="box1" VALUE=""> <INPUT TYPE="submit">