Navigator 2.0 is the most powerful version of Netscape's Web browser. Besides bringing together a collection of useful Internet-access tools, such as a mail client, a news reader, and improved support
for the developing HTML 3 standard, Navigator 2.0 adds several features that enhance the ability of Web authors to develop complete, platform-independent applications deployed and executed in the Netscape browser. Going beyond the Web browser, Navigator
Gold adds editing and development tools to the package.
These capabilities include an applications programmer's interface (API) for plug-ins. Plug-ins are program modules that dynamically extend the capability of Navigator 2.0 to handle new types of data and information, along
with JavaScript and Java, which allow the addition of flexible progammability to Web pages.
In this chapter we also take a detailed look at the main features and aspects of JavaScript, as well as review the major strengths and weaknesses of the JavaScript language and its suitability to particular tasks.
We then dive deeper into objects and how they work and take a look at properties and methodsthe building blocks of objects. We also look at the built-in objects in JavaScript and what they offer the programmer.
In this chapter we take a broad look at Navigator 2.0 and consider how JavaScript fits into the puzzle. You'll learn about the following topics:
Although Netscape Navigator started out its life as a basic Web browser, as it has grown increasingly popular, it has become much more.
Unlike earlier browsers and today's basic Web applications, Navigator 2.0 provides authors with numerous tools to step beyond the traditional constraints of HTML. Instead of simply combining text, pictures, sound and video, authors now have finer
control over document layout, fonts, and color; they are able to extend the functionality of the browser using plug-ins and Java; and they can produce interactive applications using JavaScript.
A quick look at the Netscape Web site shows that today's Navigator can do so much more than previous versionseven without special programming by Web developers. With freely available plug-ins from leading software
companies, Web authors can include native CorelDRAW graphics or Microsoft Word files in their documents, as well as view VRML (Virtual Reality Modeling Language) worlds, and view documents formatted in Adobe's device-independent Acrobat format.
On top of all this, however, Navigator 2.0 provides several tools that Web page developers and authors can take advantage of to enhance their documents and add dynamic interaction with the information they are providing on the Internet.
Frames are the most visually noticeable extension of HTML in Navigator 2.0. Using frames, authors are able to partition the screen into multiple rectangular sections. Each
section is independent of all the others, and a different URL is loaded into each frame. In addition, links in one frame can be used to update another frame, without disturbing any others.
Frames are being used today to produce fixed, banner-like mastheads for Web Pages, for menus that always stay on the screen and don't need to be reloaded or redrawn, and for forms-based searches
where the form is always available.
In addition to the obvious visual appeal of frames technology, this extension to HTML may have an added benefit in that it reduces the amount of data that may need to be requested from the server and sent to clients. On the increasingly-congested World
Wide Web, this may prove to make Web browsing slightly more efficient and reduce some of the load on over-burdened Web servers.
Figure 1.1 shows an example of how frames can be used to divide the screen and provide both a fixed masthead and a permanent menu next to several frames of dynamic information. In Figure 1.2, you can
see how choosing a menu item updated the bottom-left section of the screen without affecting the rest of the window.
Figure 1.1. Using frames provides fixed and dynamic elements.
Figure 1.2. Using a menu to update one frame.
Another exciting feature of Navigator 2.0 is the open plug-in technology. By providing an open application programmer's interface for plug-ins, Netscape has made it possible for third-party software vendors to provide the
ability to view a wide range of data and documents in the Navigator browser window. Netscape refers to objects displayed by plug-ins as Live Objects.
To date, a significant number of vendors including Corel, Paper Software, and Adobe have produced plug-ins for their own formats. (Figure 1.3 shows one such company.) Many of these will likely be extended to support JavaScript, enabling JavaScript
programs to interact with plug-ins directly and further enhancing the power of JavaScript in future versions of Netscape Navigator. At the present time there are no tools for doing this.
Figure 1.3. Paper Software's WebFX plug-in enables Navigator 2.0 to browse VRML worlds.
Using JavaScript and Java, Web developers have come up with further enhancements to Web pages beyond the ability to load multiple documents in separate frames and view new file formats.
Some of the common Java applets available today include the following:
Figure 1.4. This Web page demo by Sun Microsystems' Jim Graham uses Java to include live data feeds.
The widespread popularity of Java means that the range of uses will increase in the future, but today Java is being used primarily for cosmetic enhancements to Web pages.
By comparison, JavaScript is used to produce scripts designed to react to user and environment eventsas well as in the future being the glue to hook Java applets more seamlessly into Web pages. The following are some examples:
Figure 1.5. JavaScript prompts the user for correct information before a form is sent to a server.
JavaScript is one of the least-used components of Netscape's suite of interactivity tools (although that is quickly changing), but it could be the most significant. Not only does it bring interactive
programming within the reach of the average Web author with no formal programming experience, it can also be used to move much of the processing away from over-burdened servers to increasingly-powerful client workstations.
As opposed to the independent application files used to deliver Java applets to Web browsers, the actual source code for JavaScript scripts can be included directly in Web pages. This is distinct
from Java applets which exist independently of the HTML Web pages.
JavaScript is integrated tightly into HTML and the Navigator 2.0 browser. Developers have available to them a wide range of tools and information to interact with the currently-loaded HTML document,
as well as the current browser session.
JavaScript exposes properties related to the document windows, the history list, the loaded documents, frames, forms, and links to the programmer. In addition, JavaScript can be used to trap user events, such as changing form values or pointing at
links, so that appropriate programs can be developed for each event.
Given the tremendous popularity of Java since its introduction in 1995, it is important to take a look at the differences between Java and JavaScript. Although they are
relatedJavaScript borrows most of Java's syntax, for instancethey are fundamentally different and serve different purposes. They are complementary rather than competing with each other.
Java is much more than a language for developing Web-based applications. It is designed to compete in a market of full-fledged, general-purpose programming languages such as C, C++, Pascal and
FORTRAN. Unlike its predecessors, Java's claims to fame include the fact that it is platform-independent and that it can be used for both applications development and the development of in-line applets, or small applications, for Web pages.
Like C++ and Smalltalk, Java is object-oriented and relies heavily on the syntax and style of C++. With this comes the steep learning curve of a high-end object-oriented programming language.
Unlike most other general-purpose programming languages, Java is not compiled in the traditional sense. Instead of compiling to native machine code, the Java compiler converts source code into Java
byte codes (known as architecture-neutral byte-codes)a platform-independent representation of the Java program codewhich are then run on a machine-dependent runtime interpreter. In this way,
developers only need to develop and maintain one set of source code and compile it once, and the code can then be run using the runtime interpreters for any machine.
Like all compiled languages, though, this adds the complexity of a compilation cycle to development and, especially, debugging. However, to a certain degree like other compiled languages, an efficient runtime engine means that Java should offer better
performance than general-purpose interpreted scripting languages.
A fundamental feature of true object-oriented languages is that they are extensible. That is, programmers can create their own
classesor groupings of objects and data structuresto extend the basic classes that are part of the programming languages.
Java is no exception to this rule. Java programmers routinely create their own extensions to the base set of tools or classes.
As mentioned before, object-oriented programming languages tend to have steep learning curves, especially for non-programmers. Java is not exempt from this
difficulty.
The general consensus among beginning programmers is that learning Java is a formidable task, especially considering the complexity of the available on-line documentation on the Internet.
The base set of classes that comes with the Java distribution make it ideally suited to client-server interactions. The ability to work with URLs and talk to HTTP servers already exists. The support for applets adds the
ability to interact with user events in the client Web browser.
In addition, HotJava, the demonstration browser from Sun Microsystems, demonstrates how Java can become the means by which browsers dynamically learn to handle new protocols as that ability is
needed.
Java is famous because it can be used to develop applets that are delivered on the World Wide Web and executed in client Web browsers.
However, Java can also be used to develop complete, platform-independent GUI applications using the Java runtime interpreter.
Because of the extremely open and public nature of the World Wide Web, security is a major issue for Java and Java applets. After all, allowing application code from unknown remote machines to be
downloaded and executed on your computer system is potentially dangerous. Not only is there the potential for applets to contain viruses, but they could simply be malicious applications intent on destroying your data and rendering your computer inoperable.
To address this, Sun implemented tight security features from the earliest stages of Java development. These features include verification of bytecodes (to ensure they don't violate access restrictions and more), as well as
configurable network security that ranges from disabling network access to limiting access by an applet only to the host where the code originated, all the way to completely free network access.
Even though applets are a feature of the World Wide Web and are included as in-line applets in HTML files, they are distinct and separate
from HTML and HTML files. New HTML tags force a Web browser to initiate a new connection to the server and tell the browser where to display the applet's output on the Web page, but beyond that, applets are separate and distinct from HTML.
In contrast to Java, JavaScript joins the ranks of simple, easy-to-use scripting languages. JavaScript promises an easier learning curve than Java along with powerful
tools to add interactivity to Web pages with little effort.
JavaScript owes a lot to Java. Its syntax and basic structure are similar to Java, even if the range of functions and the style of programming can differ greatly. JavaScript started life as Netscape's own scripting language with the name LiveScript, but
in late 1995, Sun endorsed the language, and it became JavaScript.
JavaScript keeps more than just the basic syntax and structure of Java, it also borrows most of Java's flow constructs and implements some of the same security precautions, such as preventing applets from writing to the
local disk.
Unlike Java, JavaScript is an interpreted language. Whereas in Java, source code is compiled prior to runtime, in an interpreted language source code files are executed directly at runtime in
JavaScript.
Interpreted languages offer several advantagesas well as several drawbacks. Interpreted languages such as JavaScript are generally simpler than compiled languages and are easy to learn. It is often easier to develop, change, and trouble-shoot
programs because the need to recompile with each change is removed.
On the negative side, the need to interpret commands as the program is run can produce a performance hit with some interpreted languages. In the case of JavaScript, this doesn't seem to be the case.
JavaScript scripts are compiled to byte codes (similar to Java) as the script is downloaded and evaluated, and for most scripts, performance feels quite snappy.
Unlike Java, JavaScript is not fully extensible. The JavaScript model is one of a limited set of base objects, properties, methods, and data types, which provide enough capabilities to create
client-side applications.
While users can create their own objects and write functions, this is not the same as the classes and inheritance offered in Java and other object-oriented programming languages.
Since JavaScript is an object-based scripting language, this book will be devoted to learning about the objects, properties, methods, and data types available in JavaScript.
JavaScript in its current form is not designed for complete client-server interaction. Beyond analyzing, building, and invoking URLs, JavaScript can't talk directly to servers or talk different protocols. Essentially,
JavaScript is well-suited to handling client-end activity.
Still, there are indications that future versions of JavaScript will support protocols such as HTTP and FTP, but several security issues surrounding client-server interaction through JavaScript need to be addressed by Netscape before it implements these
features.
In addition, JavaScript will be part of the LiveWire Web server being developed by Netscape. LiveWire is aimed at groups and organizations developing interactive Web applications. In this role, JavaScript will provide an alternative to today's CGI
scripting for server-end programming.
Where Java is only loosely tied to HTML, JavaScript is tightly integrated into HTML files. Typically, entire scripts are in the same files as the HTML that defines a page and are downloaded at
the same time as the HTML files.
In undertaking the task of learning JavaScript, it is important to keep in mind the current status of the language and where its development appears to be headed.
Both Navigator 2.0 and JavaScript are under intense development and are constantly evolving. So, JavaScript is by definition, a language under development (as are most programming languages). In
practical terms, that means that the complete language specification is not implemented yet.
In a very real way, JavaScript is a moving target. Some of the methods and properties of the current implementation may be dropped in the next version or the final release; the actual completed language specification may change; and the way in which
some things are done could change as the language develops.
In late November, LiveScript became JavaScript in a joint announcement by Netscape and Sun that Sun would be supporting JavaScript as the Java-based open scripting standard for the Internet.
Given this support, there is little doubt that JavaScript will continue to resemble Java and that it will become the choice tool for gluing Java applets into Web pages, at least in the Netscape environment.
Essentially, this endorsement from Sun breathed life into a scripting language that very few people were paying attention to, but which is now the hot topic on the World Wide Web.
Sun Microsystems isn't the only company to support JavaScript. At the same time as Netscape and Sun made their announcement, more than 28 companies including America Online, Apple Computers, Oracle, Silicon Graphics,
Architext, and SCO announced that they would also be endorsing JavaScript as the open scripting standard for the Internet, and many indicated they were considering licensing the technology to include in their own products.
In addition to including JavaScript in its Navigator Web browser, Netscape is going to include JavaScript in its server-end products, including LiveWire, the Netscape Commerce Server and the Netscape Communications Server.
Once this happens, it is entirely possible that the momentum for Perl and Bourne Shell as the languages of choice for CGI programming will shift toward JavaScript, producing a consistent development environment at both the client and server ends.
In addition, the endorsements from numerous companies mean that JavaScript will start to appear in products from companies other than Netscape and in products other than Web browsers and servers.
In this book, we are focusing on using JavaScript in the Navigator Web browser because this is where most JavaScript development is taking place and because this is the easiest environment in which to learn and practice JavaScript.
By now, you probably have some idea of what JavaScript is and what it isn't, but let's look closer at the features you'll be learning and using throughout the course of this book.
Scripting languages have been in use long before the Web came around. In the UNIX environment, scripts have been used to perform repetitive system administration tasks and to automate many tasks for less computer-literate users. In addition, scripting
languages are the basis of much of the CGI-BIN programming that is currently used to add a limited form of interactivity to Web pages.
Examples of scripting languages include Perl, well known in CGI programming, Awk and SED (designed for intensive text processing), and even HyperTalk which, like JavaScript, is an object-oriented scripting language.
Of course, this still doesn't tell you what the main advantages of scripting languages are. Like all scripting languages, JavaScript is interpreted, which provides an easy development process; it contains a limited and easy-to-learn command set and
syntax; and it is designed for performing a well-defined set of tasks.
Because JavaScript is a scripting language, it is well-suited to implementing simple, small programs. For instance, JavaScript would ideally be suited to developing a unit conversion calculator between miles and kilometers
or pounds and kilograms. These tasks can be easily written and performed at acceptable speeds with JavaScript and would be easily integrated into a Web page. A more robust language such as Java would be far less suited to the quick development and easy
maintenance of these types of applications.
By contrast, JavaScript would not be suited to implementing a distributed CAD document display and manipulation environment. While eventually JavaScript will be a tool for integrating this type of Java applet or plug-in into a Web page, to attempt to
develop the actual applet in JavaScript would be at best, difficult and inefficient and, more likely, would be impossible.
Of course, this doesn't mean that sophisticated applications can't beand aren't being developed with JavaScript. Nonetheless, scripting languages are generally used for smaller tasks rather than full, compiled programs.
Just as JavaScript is suited to producing small programs, it is especially well-designed for repetitive, event-invoked tasks. For example, JavaScript is ideal for calculating the content of one field in a form based on
changes to the data in another field. Each time the data changes, the JavaScript program to handle the event is invoked, and the new data for the other field is calculated and displayed.
Because of the way in which JavaScript is integrated into the browser and can interact directly with HTML pages, JavaScript makes it possible to program responses to user events such as mouse
clicks and data entry in forms.
For instance, a JavaScript script could be used to implement a simple help system. Whenever the user points at a button or a link on the page, a helpful and informative message can be displayed in the status bar at the bottom of the browser window.
This adds interactivity to Web pages, makes forms dynamic and can decrease the bandwidth requirements and server load incurred by using forms and CGI programming.
Like other scripting languages, JavaScript eases development and trouble-shooting because it is not compiled. It is easy to test program code, look at the results, make changes and test it again
without the overhead and delay of compiling.
The popular phrase when referring to JavaScript is that it will "glue Java applets into Web pages." It will do this in future versions by using its
capabilities to trap user events and pass relevant information, triggered by these events, to Java applets which, in many ways, are more limited in their ability to interact with the user and the browser environment.
Object-oriented is a term that has been over-used by the media and marketing arm of the computer and software industries. Nonetheless, the fact that JavaScript has a limited object-oriented model is an important distinction.
In order to understand what it means for JavaScript to be object-based, we need to look at objects and how they work.
Fundamentally, objects are a way of organizing information, along with the methods for manipulating and using that information.
Objects provide a way to define specific pieces of data related to the item in question; these pieces are known as properties. In addition, these are supplemented by tasks that can be performed on or with that
information, known as methods. Together properties and methods make up objects.
Because of the general nature of objects, specific instances can be created for each case where they are needed. For instance, a car object could then have several instances for Toyotas, Fords, and Volkswagens.
Defining objects in this way differs greatly from the way in which information is handled in traditional procedural programming languages such as FORTRAN and C.
In these languages, information and procedures (similar to methods) are kept separate and distinct and are not linked in the way that objects are. Also, the concept of creating instances isn't as well developed in procedural languages.
JavaScript includes both built-in objects to work with elements of the currently loaded HTML document, as well as performing other useful tasks, such as mathematical calculations. It also offers the programmer the chance to create her own objects.
JavaScript offers a set of built-in objects that provide information about the currently loaded Web page and its contents, as well as the current session of Navigator. In addition, these objects
provide methods for working with their properties.
Most of the built-in objects in JavaScript are part of the Navigator Object Hierarchy. The Navigator Object Hierarchy is built from a single base object called the window object, as illustrated
in the following outline.
Window
Location
History
Document
Forms
Anchors
Table 1.1 highlights the major features of these objects.
Object |
Description |
window |
The window object provides methods and properties for dealing with the actual Navigator window, including objects for each frame. |
location |
The location object provides properties and methods for working with the currently opened URL. |
history |
The history object provides information about the history list and enables limited interaction with the list. |
|
|
In addition to the objects in the Navigator Object Hierarchy, JavaScript provides several objects that are not related to the current windows or loaded documents. Table 1.2 outlines the major features of these objects.
Object |
Description |
string |
The string object enables programs to work with and manipulate strings of text, including extracting substrings and converting text to upper or lower case characters. |
Math |
The Math object provides methods to perform trigonometric functions, such as sine and tangent, as well as general mathematical functions, such as square roots. |
|
|
In addition to a wide range of built-in objects, as a JavaScript programmer, you can create your own objects to use in your scripts.
For example, if you need to build an object in JavaScript to represent the different types of airplanes sold by an aircraft manufacturer, you would have several pieces of information related to the airplane that you would
want included in the object, including the following:
Properties are like variables in traditional languages, such as C and Pascal. Variables are named containers which are used to hold pieces of data, such as numbers or text. Variables are discussed in more detail in Chapter
3, "Working with Data and Information."
So, in JavaScript, if you call your object airplane, these properties might be referred to as:
airplane.model airplane.price airplane.seating airplane.cargo airplane.maxspeed airplane.fuel
Of course, having this information isn't worth much without ways to use the information. For instance, in this example, you want to be able to print out a nicely formatted description of the aircraft or be able to calculate
the maximum distance the plane can travel based on the fuel capacity.
In object-oriented terminology, these tasks are known as methods. Like properties, your methods might be referred to as:
airplane.description() airplane.distance()
Objects can also include other objects in much the same way as properties and methods. For instance, the airplane manufacturer may want to include an object inside his object definition to handle information about the number
of planes in use worldwide, who is using them, and their safety records. This information, along with methods for working with the information, could be combined into an object called airplane.record. This object could then include properties and methods
such as:
airplane.record.number_in_use airplane.record.crashes
What you have created is a general description of an object that defines the information you want to work with and the ways you want to work with it. These general descriptions of objects are known as classes. In
object-oriented programming, then, you can create specific instances of the class as needed.
For instance, in this example, the airplane manufacturer might want to create an instance of the airplane object for its newest aircraft, the SuperPlane. If this instance were created, then a program could assign specific values to the properties of the
new instance by referring to superplane.price, superplane.model, and so on. Likewise, a description of the new plane could be printed out using superplane.description().
JavaScript offers several strengths to the programmer including a short development cycle, ease-of-learning and small size scripts. These strengths mean that JavaScript can be easily and quickly
used to extend HTML pages already on the Web.
Because JavaScript does not require time-consuming compilation, scripts can be developed in a relatively short period of time. This is enhanced by the fact that most of the interface features, such as dialog boxes, forms,
and other GUI elements, are handled by the browser and HTML code. JavaScript programmers don't have to worry about creating or handling these elements of their applications.
While JavaScript may share many similarities with Java, it doesn't include the complex syntax and rules of Java. By learning just a few commands and simple rules of syntax, along with understanding the way objects are used in JavaScript, it is possible
to begin creating fairly sophisticated programs.
Because the World Wide Web, by its very nature, is platform-independent, JavaScript programs created for Netscape Navigator are not tied to any specific hardware platform or operating system. The same program code can be
used on any platform for which Navigator 2.0 is available.
JavaScript programs tend to be fairly compact and are quite small, compared to the binary applets produced by Java. This minimizes storage requirements on the server and download times for the
user. In addition, because JavaScript programs usually are included in the same file as the HTML code for a page, they require fewer separate network accesses.
As would be expected, JavaScript also has its own unique weaknesses. These include a limited set of built-in methods, the inability to protect source code from prying eyes, and the fact the
JavaScript still doesn't have a mature development and debugging environment.
Early versions of the Navigator 2.0 beta included a version of JavaScript that was rather limited. In the final release of Navigator 2, which was the current version at the time of writing this
book, the number of built-in methods had significantly increased, but still didn't include a complete set of methods to work with documents and the client windows. Still, the current version is about as complete as we will get until Navigator 2.1.
Because the source code of JavaScript script presently must be included as part of the HTML source code for a document, there is no way to protect code from being copied and reused by people who
view your Web pages.
This raises concerns in the software industry about protection of intellectual property. The consensus is that JavaScript scripts are basically freeware at this point in time.
Most well-developed programming environments include a suite of tools which make development easier and simplify and speed-up the debugging process.
At the time of writing this book, there were no JavaScript-specific tools available for this purpose, although some people had begun developing Web-based applications (using JavaScript) to achieve some of this.
JavaScript is one of several key components in Navigator 2.0 designed to help Web developers produce interactive applications on the Internet. Other features include support for plug-ins, frames, and of course, Java.
Where Java is compiled, object-oriented, complex, and distinct from HTML, JavaScript is interpreted, object-based, simple to use and learn, and tightly integrated with HTML.
JavaScript exposes properties of the current browser session to the programmer, including elements of the currently loaded HTML pages, such as forms, frames, and links.
In this chapter we also took a look at the implications of the fact that JavaScript is a scripting language and took a close look at what objects are, how they are used in JavaScript, and took a broad look at the built-in objects in JavaScript.
You learned that, while JavaScript offers many benefits including a quick development cycle and platform independence, it still has drawbacks.
In the next chapter, you will begin taking a look at the specifics of developing JavaScript scripts and will work on your first script.
Q: I've only used visual programming tools for making Web pages, can I learn JavaScript? How will knowing JavaScript make my home page better?
A: While it's true that programming in JavaScript is more similar to programming in C than using a visual programming tool, most JavaScript programming is simple enough to make it easy for the complete beginner.
In addition, the development of interfaces to JavaScript programs almost entirely involves the use of HTML and HTML forms, which can be developed in a visual environment using several HTML development tools, including Navigator Gold from Netscape.
If you learn JavaScript, you will be able to add interactivity to Web pages. For instance, if a user enters data in a form, a result can be calculated and displayed for the user. Similarly, if the user moves the mouse over a link or button, help
information can be displayed in the status bar of the Navigator window.
Q: I want to add interactivity to my Web pages. Should I learn Java or JavaScript?
A: Java and JavaScript are not competitors. They are complementary programming languages which both extend the functionality of Web browsersin this case Navigator 2.0.
You will find that Java is suited to a different set of tasks than JavaScript. For instance, a viewing tool for CAD documents would need to be developed using Java applets while an interactive HTML form could only really be developed using JavaScript.