Chapter 6

The Scripting Model

by Evangelos Petroutsos


CONTENTS

In the previous chapters, you learned how to write applications with VBScripts and how to program the controls to activate your pages. VBScript can also help control the browser's window, which is the container where your pages get displayed and your code is executed. In this chapter, you explore the objects that let you control the environment in which your VBScript applications will be executed. In terms of traditional programming, you've learned the language. In this section, you learn how to program the environment of the application, too.

ActiveX controls, the objects you use to build the interface of the application, are manipulated through their properties and methods. Internet Explorer provides another set of objects, with their own properties and methods. These objects enable you to manipulate the environment of Internet Explorer itself. Because Internet Explorer is the operating system for your VBScript applications, you can think of these objects as the operating system's controls. The browser's window is such an object. So far, this window has served as nothing more than the container for your application. It was the environment in which VBScript applications were executed. Now, you learn how to control the window object programmatically. You will see that it is possible to load another document in the browser from within your code; it's even possible to create pages on the fly with VBScript code. You will also learn how to control some of the browser's functionality, such as moving back and forward through the history list from within your applications. This process is equivalent to clicking the Back and Forward buttons on your browser, but you'll be able to perform these actions from within your VBScript application.

The material of this chapter assumes a basic knowledge of HTML authoring. You should understand the structure of an HTML document and the HTML tags used in the examples and their attributes. Some topics that are fairly new to Web authoring, such as floating frames, will be explained in the course of the chapter. To make the best of the HTML object model, however, you should at least have a familiarity with HTML authoring.

Windows, Documents, and Frames

The Internet Explorer scripting model is made up of a hierarchy of objects, with the window representing the most important object, the document and the frames objects. The discussion of the Internet Explorer scripting model begins with an overview of these three objects, the properties and methods they provide, and how you can use them to control Internet Explorer. The following sections discuss all the objects of the scripting model and give a number of examples to illustrate them. If you're wondering why Internet Explorer is controlled through objects and why the objects have a hierarchy, you need to read this chapter. Internet Explorer is an OLE control that exposes certain objects, such as its window and the current document. These objects, in turn, expose certain properties, and by manipulating these properties you can actually manipulate Internet Explorer itself.

The various objects through which you can control the behavior of Internet Explorer form a hierarchy. The window object is the top level object in this hierarchy and acts as a container for all other objects. This object is the browser's window you see on-screen; moreover, every parameter of the window you can adjust through VBScript code is a property of the window object. For example, the name of the window is a property of the window object. You can find out the name of the window from within your script with a statement like the following one:


wName=window.name

Another property of the window object is the status property, the text displayed in the status bar of the browser window. You can find out the current status message with the statement:


statusMessage=window.status

You can also set the status message with statements like these:


window.status="Thanks for visiting our site!"

or


window.status="Date "& date & " Time " & time

The window object's property you will use the most is the document property, which represents the document displayed on the window. This property is actually another object, with its own properties. The document has a background color, whose value can be manipulated with the document's bgColor property. To access the bgColor property of the document object, you can use a statement like the following one:


window.document.bgColor=red

Because the document object is the default property of the window object, you can omit the window identifier in the previous line:


document.bgColor=red

The window and the document objects are visible on-screen. Other objects exist that are not visible, but which enable you to control the behavior of Internet Explorer through their properties. The location object is a property of the document object, which enables you to manipulate the URL of the document displayed in the window. One property the location object provides is called href, and is the URL of the document being displayed. This is the URL displayed in Internet Explorer's Address box. To find out the URL of the current document, you must access the href property of the location object of the document object:


thisURL=window.document.location.href

As usual, you can omit the window identifier. Even so, you have a rather lengthy statement, but don't let it intimidate you. The URL is a location property and the location object applies to the document object. Thus, the location is a property of the document, and not the window. href is a property of the location object, which in turn is a property of the document object, which in turn is a property of the window object. You must write down a sequence of objects, starting with the top level object (the window object) and work your way down to the lower-level object whose property you want to access.

A window can also contain frames, which you can access through the frames object. The frames object is an array of objects, the first frame being frames(0), the second one frames(1), and so on. To control the background color of the document in the first frame, you must access the bgColor property of the document of the first frame. Each frame has its own document property similar to the window object. This time we want to access the document of a frame, which in turn is a property of the window object. Instead of getting the window.document.bgColor property as you saw earlier, you must access the document.bgColor of the frames(0) property of the window object:


window.frames(0).document.bgColor

Likewise, you can specify the URL of a document to be displayed in a frame. You start with the href property of the location object, which now must be applied to a frame, and not the window's document. To cause another document to be displayed in the first frame of the window, you must use a statement like:


window.frames(0).location.href

As you can see, the same object can be attached to multiple containers (which are also objects). The window has its own document object, and the document has a location property. If the window contains frames, however, each frame in the window has its own location property. You may find this behavior confusing at first, but you will soon get the hang of it.

In Microsoft's colorful terminology, each entity you see on the browser's window is an object. Objects "expose" some of their properties, which enables you to manipulate them. Some of these properties represent objects themselves, which expose their own properties. The window object exposes the name property, which enables you to examine the name of a window from within your code. To manipulate the background color of the document on the window, you must first access the document property of the window (window.document) and then the bgColor property of the document object (window.document.bgColor).

In the following sections, you explore the objects of the scripting model and their properties, as well as their methods, which enable you to control the Internet Explorer's environment from within your code. The text begins with the window object and one of its most important properties, the document object. As you will realize, the document object offers tremendous flexibility over the appearance and function of your Web pages, and it appears in many examples for this section.

The following list provides the other objects of the window object, which you will explore in this chapter:

historyhistory is an object you can use to access the history list of the current window. This is a list of the URLs visited already.
navigatorThe navigator object contains information about the browser, such as the name of the browser and its version.
locationThe location object provides information about the window's current URL.
documentThe most important object of all. It's the actual document in the current window.

The window Object's Properties

The following paragraphs explain the various properties of the window object and offer short examples that demonstrate the syntax of the various properties. In the sections that describe the other objects of the scripting model, you will find more elaborate examples of the various properties of the window object's properties.

name

name is a read-only property that returns the name of the window. To create a named window, you must use the TARGET attribute with one of the HTML tags to which it applies. For example, the <A> tag is frequently used with the TARGET attribute, which tells the browser to display the destination HTML document in another window. The HTML line


Click <A HREF="http://www.microsoft.com">here</A> to visit the Microsoft Web site.

generates a hyperlink, which displays the root document of Microsoft's Web site when activated in the same window that contains the hyperlink. If you specify the TARGET attribute, however, the same document will appear in a separate window:


Click <A HREF="http://www.microsoft.com" target="MS">here</A> to visit the Microsoft Web site.

If a window with the name MS exists already, the document will be displayed in it. If such a window doesn't exist, a new window opens and the document appears there. You can later refer to this window by its name. For example, you can set the string to appear in the window's status bar using the status property.

parent

The parent property returns the name of the parent window, which contains the specific window. The parent property of the window object is an object itself, and through its properties, you can adjust the appearance of the parent window.

opener

The opener property returns the window object that opened the current window. The opener property does not return a window name or another window property. It returns an actual object that you can use to access the properties of the window from which the current window was opened. To find the name of the opener window, use the Name property, as in the following line:


MsgBox "My parent window is " & opener.name

self

self is a window object that represents the current window, but, although mentioned in Microsoft's documentation, it's not yet supported by Internet Explorer 3.0.This property operates similarly to the parent and opener properties, in the sense that it returns a window object, and not the name of the window. To find out the status message of the current window, you could use the status property of the self object:


If self.status = "VBScript" Then

    self.status = "ActiveX"

Else

    self.status = "VBScript"

End If

If you place this If structure in a Timer event's handler, the message on the browser's status bar would alternate between the strings VBScript and ActiveX.

top

The top property returns an object that represents the topmost window.

location

The location property returns another object, the location object, which is described in detail in a later section. The most important property of the location object is the href property, which returns or sets the URL of the current window. The statement


MsgBox window.location.href

displays the URL of the current window in a message box. To activate another URL from within your code (in other words, without relying on the user to click on a hyperlink, or the browser's Back button), use a statement such as:


window.location.href="www.microsoft.com"

defaultStatus

This property sets the default text in the status bar. See the description of the status property to find out how you can display a message in the browser's status bar.

status

The status property returns or sets the text displayed in the status bar. The statement


window.status = Now

displays in the status bar the date and time the document was opened. To update the status bar, use the previous statement form within a Timer event handler. Figure 6.1 shows two windows with different status messages. The two status messages were displayed with the statements

Figure 6.1 : With the status property of the window object, you can control the message displayed in the browser windowıs status bar.


window.status="Welcome to SAMS Publishing"

and


window.status="Today's date is " & date & " and the time is " & time

frames

This property returns an array of objects, which are the frames in the current window. Use it to access the various properties of a frame object, such as its name or its URL:


MsgBox "The name of the first frame is " & window.frames(0).location.href

MsgBox "The document displayed in the first frame is located at " & window.frames(0).location.href

The location property of the window object controls the contents of the window (through its property href). When you apply the location property to a frame object, it controls the contents of the specific frame.

Methods

Apart from its properties, the window object provides several methods. The methods are predetermined actions that the window object knows how to perform, such as how to display a message and get input from the user, or how to navigate through the history list (the Web sites visited during the current session) of the window. The window object's methods appear next:

alert

The alert method displays an alert message box. The alert message box is very similar to the regular message box of the Windows 95 user interface. It displays a message and remains on the screen, and the execution of the script is suspended until the user clicks the OK button. You can use the alert method for displaying messages to the user; its syntax is


alert("Thanks for visiting our site")

confirm

confirm displays a message box similar to the alert method, only this box has two buttons, OK and Cancel. The confirm method returns the value True if the OK button is clicked and the value False if the Cancel button is clicked. This method frequently is used to notify the user that an unusual or irrevocable action is about to take place, such as the transmission of Form data to the server. Here's how the confirm method is typically used:


x=window.confirm("Do you want to submit the data?")

if x=True Then Form.submit

Figure 6.2 : The alert, confirm, and prompt methods display boxes that operate similarly to the VBScript MsgBox() and InputBox()functions.

prompt

The prompt method prompts the user for data, much like the InputBox() function. The prompt method accepts two arguments, the prompt for the user and an optional default response, and returns the data supplied by the user. The following statement prompts the user for the name of the browser:


browserName=window.prompt("What's your favorite browser?", "Internet Explorer")

Whatever the user has entered in the box gets stored in the browserName variable, which can later be used in the code. If the user simply clicks OK without entering any information, the default response is returned.

open

The open method opens an existing window, or creates a new one and displays a document in it. This method syntax can become quite lengthy because it accepts a number of arguments:


[newwindow = ][window.]open url, target, ["[toolbar=bool] [, location=bool]

[, directories=bool][, status=bool][, menubar=bool][, scrollbars=bool]

[, resizeable=bool][, width=pixels][, height=pixels]"][, top=pixels][, left=pixels]

The arguments in square brackets are optional. The simplest form of the open method is


window.open url, target

where url is the URL of the document to be displayed in the new window and target is the name of the window in which the document will appear. If the window specified with this name exists, this window's contents get replaced by the new document. If not, a new window with this name is opened and the document displays in it. This argument is identical to the TARGET attribute of the <HREF> tag.

The remaining arguments are set to Boolean values (yes/no, or 1/0) and control the appearance of the window. To hide the new window's toolbar, use the argument "toolbar=no", and to prevent the user from resizing the window, use the argument "resizeable=no". The last four arguments, which are specified in pixels, don't need to be enclosed in quotes. The arguments width and height determine the window's dimensions, and the arguments top and left determine the window's position on-screen, measured from the screen's top-left corner.

The return value is a window object, which you can use later to close the window. The statement


window.open "http://www.microsoft.com", "MSwindow", "toolbar=no", "menubar=no",
"resizeable=no", width=600, height=400

opens the window MSwindow (or creates a new one by that name, if it doesn't exist) and displays the home page of the Microsoft Web site. The MSwindow window has no toolbar and menu. Furthermore, it is 600 pixels wide and 400 pixels tall, and can't be resized. The width, height, top, and left arguments are all mentioned in Microsoft's documentation, but they don't work with version 3.0 of Internet Explorer. If you create a script with the previous line, Internet Explorer 3.0 will produce an error message. Omit the size specification for the new window (the last two arguments), and the open method will work fine. It will display Microsoft's Web site in a window without the usual menu or the toolbar.

You can find the document WindowOpen in this chapter's folder on the CD. The WindowOpen document contains a number of command buttons that act as hyperlinks to various sites. Every time the user clicks one of the buttons, the home page of the corresponding Web site appears in a separate window.

The HTML code of this document is straightforward. It displays a heading and the instructions, and places six command buttons next to its other. The code in each command button's Click event handler invokes the open method to display a URL in a separate window. The contents of the WindowOpen.htm file appear in the following code:


<HTML>

<HEAD>

<TITLE>WindowOpen</TITLE>



<SCRIPT LANGUAGE=VBS>



Sub MS_onClick()

    window.open "http://www.microsoft.com", "window1"

End Sub



Sub SAMS_onClick()

    window.open "http://www.mcp.com/sams", "window2"

End Sub



Sub MSN_onClick()

    window.open "http://www.msn.com", "window3"

End Sub



Sub CLGRI_onClick()

    window.open "http://www.caligari.com", "window4"

End Sub



Sub INTEL_onClick()

    window.open "http://www.intel.com", "window5"

End Sub



Sub NSCAPE_onClick()

    window.open "http://www.netscape.com", "window6"

End Sub



</SCRIPT>



<BODY>

<FONT FACE="Verdana">

<CENTER>

<H1>Top Web Sites</H1>

<H4>Click on the following buttons to see some of the best Web sites around.

Each Web site will be displayed in a separate window and, if you wish, you 

can open them all at once.</H4>

<P>

<INPUT TYPE=BUTTON NAME="MS" VALUE="Microsoft">

<INPUT TYPE=BUTTON NAME="SAMS" VALUE="SAMS">

<INPUT TYPE=BUTTON NAME="MSN" VALUE="MS Network">

<INPUT TYPE=BUTTON NAME="CLGRI" VALUE="Caligari">

<INPUT TYPE=BUTTON NAME="INTEL" VALUE="Intel">

<INPUT TYPE=BUTTON NAME="NSCAPE" VALUE="Netscape">

</P>

</CENTER>

</BODY>

</FONT>

</HTML>

Only the first two command buttons and their code appear here. The other ones function in a similar way.

Open the WindowOpen project and experiment with the various arguments of the open method. Try opening the Internet Explorer window without the toolbar and menubar; you can also make them resizeable or not.

The open method has a behavior similar to that of hyperlinks inserted with the <A> tag; however, it gives you more control over the appearance of the new window. The real benefit of using the open method, though, is that it enables you to specify the target at runtime. On the other hand, the destination of the <A> tag must be furnished at design time and can't change when the document is viewed. With the open method, you can navigate to any URL, even a user-supplied URL.

close

The close method closes an open window. If you have opened a window with the following statement


newWindow=window.open "www.msn.com" "w1"

you can close it by calling the close method of the newWindow object:


newWindow.close

setTimeout

The setTimeout method sets up a timer to call a function after a specified number of milliseconds. The syntax of the method is


ID = window.setTimeout expression, msec, language

where ID identifies the timer object, and can be used with the clearTimeout method, which cancels the timer. expression is the name of a function that will be called when the timer object times out; msec is the number of milliseconds that must pass before the function is called; and language identifies the scripting language of the function (VBScript or Javascript). As usual, the window prefix is optional.

If the user hasn't already switched to another document, you can use the setTimeout method to take some action on a document after so many seconds. For example, you can invoke the method


window.setTimeout GoURL, 10000, VBScript

and supply the following GoURL() subroutine:


Sub GoURL()

    window.document.location.href="http://www.someserver.com"

End Sub

If the user hasn't followed a hyperlink to another page within 10 seconds after the window is opened, the browser will display the home page at the site www.someserver.com.

clearTimeout

This method clears the timer with a particular ID. Its syntax is


window.clearTimeout ID

where ID is the value returned by the setTimeout method.

navigate

The last method of the window object switches to a particular URL, which is supplied as an argument. The statement


window.navigate "http://www.msn.com"

instructs the browser to connect to the Microsoft Network site and display the site's home page. This method operates identically to setting the window's location.href property to the desired URL.

The document Object

The next object in the scripting model is the document object. You will use this object most often in programming your Web pages, and this section discusses its properties and methods in detail. The document object represents the HTML document displayed on the browser's window or one of its frames. Through its properties and methods you can manipulate the appearance or even the contents of the document. The bgColor property, for example, enables you to read or set the document's background color, and the title property enables you to read the document's title.

The document object has an extremely flexible method, the write method, which you can use to write strings on the current document. This method enables you to create documents on the fly; you'll see quite a few examples of this technique in action in this and following sections.

The document Object's Properties

The following paragraphs explain the various properties of the document object and offer short examples that demonstrate the syntax of the various properties. In the sections that describe the other objects of the scripting model, you find more elaborate examples of the various properties of the document object.

linkColor

linkColor returns or sets the color of the links in the document. This property is equivalent to the LINK attribute of the <BODY> tag. To set the color of the links on the current document to a value other than the default value, assign the hexadecimal value of a color, or a color name, to the linkColor property:


document.linkColor=yellow

document.linkColor=#00FFFF

Both statements set the color of the hyperlinks in the current document to yellow.

aLinkColor

Returns or sets the color of the active link in the document. The active link represents the one under the mouse pointer as the mouse button is pressed and not released. The current implementation of Internet Explorer does not support this property, and the <BODY> tag has no equivalent attribute. For the syntax of the property and an example, see the linkColor property.

vLinkColor

Returns or sets the color of the links that have been visited already. vLinkColor is equivalent to the VLINK attribute of the <BODY> tag. For the syntax of the property and an example, see the linkColor property.

bgColor

Returns or sets the document's background color. To change the background property of the current document, set the document's bgColor property to a color value. Both statements set the document's background color to green:


document.bgColor =#00FF00

document.bgColor="green"

fgColor

Returns or sets the document's foreground color. It has the same syntax as the bgColor property.

anchor

anchor is a property of the document object, and like some other properties, it's an object. The length property of the anchor object returns the number of anchors in the document. The individual anchors are stored in the anchors array, whose elements can be accessed with an index. anchors(0) is the name of the first anchor in the document (its value is the NAME attribute of the <A> tag that inserted the anchor in the document), anchors(1) is the second anchor, and so on. The following statements display the number of anchors in the current document in a message box:


TotalAnchors = Document.Anchors.Length

MsgBox "The document contains "& TotalAnchors & "anchors"

You can also scan all the anchors in a document with a loop like the one that follows:


For i=0 to TotalAnchors-1

    ThisAnchor=Document.Anchors(i)

    {do something with this anchor}

Next

Scanning the anchors of the current document from within the same document's script section doesn't seem very practical. You can, however, open another document in a frame and access the anchors of the frame with the Frame(1).Document.Anchors array. For another example, see the DocumentLinks example later in this chapter.

link

The link property functions similarly to the anchor property, but instead of the anchors, it represents the hyperlinks in the current document. Like the anchors array, the links array is a property of the document, which represents the only object that may contain links.

form

The form object represents a form in an HTML document. All the form objects on the document can be accessed through the forms array, whose index starts at zero. forms(0) is the first element, forms(1) is the second form, and so on. The form object's properties are as follows.

action

Returns a string containing the current form action, which is the URL of a CGI application.

encoding

Returns or sets the encoding for the form. Its value must represent a valid MIME type, such as text/html.

method

Returns or sets the method for submitting the form data to the server, and its value must be GET or POST.

target

Returns or sets the name of the target window where the result of the form processing will appear.

elements

The elements property is an array with the controls on the form. The length property of the elements object returns the number of controls on the form. The following lines scan all the controls on the first form on the current page:


For i=0 to forms(0).elements.length

    ControlName=forms(0).elements(i).name

    {do something with the current element}

Next

The form object has a method too, the submit method. This method causes the form data to be submitted to the browser. Chapter 20, "CGI and VBScript," discusses the submit method.

lastModified

Returns the date the current document was last modified. You can use the lastModified property of the document object to display the date and time it was last modified, without having to hard-code this information in the document itself.

title

The title property returns the current document's title. This property is read-only and won't allow you to change the document's title at runtime.

cookie

The cookie property enables you to set up client-side cookies. A cookie represents a message you can store on the client computer and read from another page, or the next time the same client loads your page. Cookies enable you to customize your pages for each client by maintaining information between sessions. The cookie property makes it possible for your script to actually store a string (or cookie) on the client computer and recall it at a later time. Because this property provides such a flexible and powerful mechanism in Web authoring, this text has devoted an entire chapter to the topic. (See Chapter 14,"Customize Your Web Page with Cookies.")

referrer

Returns the URL of the referring document.

The document Object's Methods

Apart from its properties, the document object provides five methods, through which you can manipulate its contents. The methods of the document object may not number as many as its properties; however, these methods provide enough to make the document the most flexible object among the HTML scripting objects. This section provides a short description of the document object's methods, as well as a few examples that demonstrate how these methods get used. Actually, most of the examples make use of the methods; consequently, this chapter gives you a thorough explanation of the document object's methods.

write string

Writes the string variable to the current document. The string gets inserted in the current document at the current position, and it doesn't appear until the close method is called.

writeLn string

Places the string variable into the current document with a new-line character appended to the end. The new-line character is ignored by the browser, so the writeLn method operates practically the same as the write method.

open

Opens the document for output. The current contents of the document are cleared, and new strings can be placed in the document with the write and writeLn methods.

close

Updates the screen to display all of the strings written after the last open method call.

clear

Clears the contents of the document.

The common sequence of methods used to place data in the current document is


Document.open

Document.write "Welcome to VBScript Unleashed"

Document.close

Instead of using a string enclosed in quotes, you can write a variable to the document, which could be the result of a calculation or a string that's calculated on the fly at the client's side (an expression that depends on the current day, for instance). The most interesting aspect of the write and writeLn methods is that their argument may also contain HTML tags. For instance, the statements


Document.write "<CENTER>"

Document.write "<H1>Welcome to VBScript Unleashed</H1>"

Document.write "<H3>by SAMS"</H3>"

Document.write "</CENTER>"

will cause level 1 and level 3 headings to appear and be centered on the browser's window. The document object's methods are quite flexible, and the following sections will present a few more examples.

Using the document Properties and Methods

This section shows a few interesting authoring techniques that make use of the properties of the Document object. You start with the color properties, which are the fgColor, bgColor, linkColor, aLinkColor, and vLinkColor. You can assign a value color to these properties, either by name (red, yellow, orange, and so on) or by hexadecimal representation. Only 16 color names exist, and they represent the names of the basic colors. To assign a color value by name, use one of the color names shown in Table 6.1. The color names are not case-sensitive, but you can't make up other color names. You must use one of the valid names.

Table 6.1. Valid names for the document's color properties.

Color property
Hex value
Aqua
#00FFFF
Black
#000000
Blue
#0000FF
Fuchsia
#FF00FF
Gray
#00E000
Green
#008000
Lime
#00FF00
Maroon
#800000
Navy
#000080
Olive
#808000
Purple
#800080
Red
#FF0000
Silver
#C0C0C0
Teal
#008080
White
#FFFFFF
Yellow
#FFFF00

Specifying colors by name is the most flexible method because you are limited to 16 colors. You can also specify colors by their hexadecimal values, and this method enables you to specify any color value you can imagine. The problem with this approach, however, is coming up with the proper hexadecimal value.

To handle color, computers use three basic colors: red, green, and blue. Each color is represented by a triplet, or RGB triplet, with the intensities of these three colors. The intensities are usually expressed as percentages, with 0 corresponding to the absence of a color component and 1 corresponding to full intensity. The triplet (0.25, 0.5, 0.20) represents a color in which the red component has 25% of the full intensity, the green component has 50% of the full intensity, and the blue component has 20% of the full intensity. Because computers internally use one byte for each color component, it's also common to express the three color components with byte values (a number from 0 to 255). The previous RGB triplet could also appear as (64, 128, 51). The triplet (1, 0, 0) shows a pure red tone, because the red component has full intensity and the other two components are missing. The triplet (0.5, 0.5, 0) represents a mid-magenta tone, as it contains equal percentages of the red and green components and no blue. Even the colors black and white can appear as RGB triplets. The triplet (0, 0, 0) is black, because all colors are missing, and the triplet (1, 1, 1) is white, because it contains all three components in full intensity.

If you start with the byte form of the RGB triplet and place the hexadecimal representation of each color component next to each other, you come up with a hexadecimal number that represents the corresponding color. The hexadecimal value of the decimal number 128 is 80, and the hexadecimal number for the RGB triplet (128, 128, 128) is 808080. To use this value as color value in HTML, you must prefix it with the symbol #, as in #808080.

VBScript provides the Hex() function, which accepts a decimal number as an argument and returns its hexadecimal representation as a string. To specify a mid-yellow tone, such as (0, 128, 128), use the Hex() function to convert these values to hexadecimal numbers and then append them to each other, with the following statement:


colorValue="#" & Hex & Hex(128) & Hex(128)

Then, you can assign this value to any of the color properties of the document object (bgColor, fgColor, aLinkColor, and so on).

Armed with this information, you can now look at a few examples that show how to use the document object's properties and methods.

A Self-Modifying Document

Now look at a couple of examples that use the color properties of the document object. The page shown in Figure 6.3, called WeeklyPage, is in this chapter's folder on the CD. This page has a different background color for each weekday. As you can guess, it combines the WeekDay() VBScript function with the bgColor property of the document object. The WeekDay() function returns a number between 1 and 7, which corresponds to the weekday. The script uses the value returned by the WeekDay() function to select one of seven colors for the document's background color.

Figure 6.3 : This document has a different background color, depending on the day of the week it was opened.

The following HTML code shows the script that produced this page:


<HTML>

<HEAD>

<TITLE>WeeklyPage</TITLE>

<SCRIPT LANGUAGE=VBS>

Dim BColor(7)



BColor(1)="Red"

BColor(2)="Blue"

BColor(3)="Teal"

BColor(4)="Yellow"

BColor(5)="Orange"

BColor(6)="Cyan"

BColor(7)="Silver"



Document.bgColor=BColor(WeekDay(Date))



Document.write "<BODY>"

Document.write Date

Document.write "<P>"

Document.write "<FONT FACE='Verdana'>"

Document.write "<H1>VBScript Unleashed</H1>"

Document.write "<B>Learn how to</B><P>"

Document.write "<UL>"

Document.write "<LI>activate your Web pages with VBScript<BR>"

Document.write "<LI>use Layouts and ActiveX Controls<BR>"

Document.write "<LI>optimize your VBScript code<BR>"

Document.write "<LI>customize your pages with cookies<BR>"

Document.write "<LI>develop intranet applications<BR>"

Document.write "<LI>and much, much more"

Document.write "</UL>"

Document.write "</BODY>"

</SCRIPT>

</HTML>

Notice that the code sets the color value of the document's bgColor property as soon as it's loaded and then places all the other elements on the page. The entire document is generated on the fly with the write method. This example shows exactly what makes the document such a flexible object. Of course, outputting the HTML commands that will produce the desired output with the write method takes quite a bit of typing, but you can automate this process with a simple program that reads actual HTML code and creates write statements whose arguments are the lines of the HTML code. You must make sure that the HTML code uses single quotes (see the line that changes the font of the document), which will not interfere with the double quotes surrounding the write method's arguments.

Color Cycling

Another interesting trick is to rapidly cycle the background color through a range of colors right before loading a new page. If the page's background color is red, you can start with a black background color, which swiftly changes from black to red and then remains red for the rest of the session. Unfortunately, this effect can be depicted on a page, so you must open the FadeColor page and see how it behaves as it loads the page. It starts with a black background that gradually shifts to red. The entire effect lasts less than a second, but it's quite impressive. To see the effect again, click on the Refresh button.

The code that produces this effect is surpassingly simple. It cycles the background color through a range of color values from black to red, with a For...Next loop:


<SCRIPT LANGUAGE=VBS>

For i=0 to 255 step 3

    colorVal= "#" & Hex(i) & Hex(0) & Hex(0)

    Document.bgColor=colorVal

Next

</SCRIPT>

You can change the step to make the effect faster or slower, and you can also change the arguments of the Hex() function to cycle the background color from any initial value to any final value. This code is placed in the <SCRIPT> tag and outside any procedure so that it will be executed as soon as the HTML document starts loading and before any other element appears. If you attempt to cycle the background color after placing the strings or any other element on the page, the entire page will flicker. The smoothest color cycling is achieved with gray tones. For example, you can start from white and move slowly to a mid-gray tone with a loop like this one:


For i=0 to 128 step 2

    colorVal= "#" & Hex(i) & Hex(i) & Hex(i)

    Document.bgColor=colorVal

Next

A characteristic of gray tones is that all three color components are the same.

A Yearly Calendar

The previous example shows how to send straight HTML code to the current window. It's an interesting technique, but you can achieve the same by supplying the equivalent HTML document. The example in this section demonstrates the flexibility of the document object's write method, namely how to create documents that produced different output on different systems, depending on the user's actions. The Calendar project displays a tabular arrangement of Command buttons with the names of the months, as shown in Figure 6.4. The user can click on a month's name and see the corresponding calendar. (See Figure 6.5.) The monthly calendar is generated on the fly with VBScript code. The actual calendar doesn't react to a mouse click, but once you understand how it was generated, you can enhance the application by making certain days hyperlinks to other files on the server (for example, you can display major events, project deadlines, and so on). You can even add code behind the digits of the days.

Figure 6.4 : The Calendar application starts by displaying the months of the year. To see a monthıs calendar, click the corresponding button.

Figure 6.5 : A monthly calendar, as displayed by the Calendar application. To return to the previous screen, click the Refresh button.

The complete listing of the project is shown here. The HTML lines that display the twelve month names as command buttons are the document's body, and the rest of the code is the script that creates the current month's calendar.


<HTML>

<HEAD>

<TITLE>Yearly Calendar</TITLE>

<SCRIPT LANGUAGE=VBS>

Sub JANUARY_onClick()

    DisplayMonth(1)

End Sub



Sub FEBRUARY_onClick()

    DisplayMonth(2)

End Sub



Sub MARCH_onClick()

    DisplayMonth(3)

End Sub



Sub APRIL_onClick()

    DisplayMonth(4)

End Sub



Sub MAY_onClick()

    DisplayMonth(5)

End Sub



Sub JUNE_onClick()

    DisplayMonth(6)

End Sub



Sub JULY_onClick()

    DisplayMonth(7)

End Sub



Sub AUGUST_onClick()

    DisplayMonth(8)

End Sub



Sub SEPTEMBER_onClick()

    DisplayMonth(9)

End Sub



Sub OCTOBER_onClick()

    DisplayMonth(10)

End Sub



Sub NOVEMBER_onClick()

    DisplayMonth(11)

End Sub



Sub DECEMBER_onClick()

    DisplayMonth(12)

End Sub





Sub DisplayMonth(imonth)

dim MonthName(12)

MonthName(1)="January"

MonthName(2)="February"

MonthName(3)="March"

MonthName(4)="April"

MonthName(5)="May"

MonthName(6)="June"

MonthName(7)="July"

MonthName(8)="August"

MonthName(9)="September"

MonthName(10)="October"

MonthName(11)="November"

MonthName(12)="December"



document.clear

document.write "<CENTER>"

document.write "<FONT FACE='Verdana' SIZE=5>"

document.write MonthName(imonth) & " " & Year(date)

document.write "<P>"

document.write "<TABLE CELLPADDING=10 BORDER><TR>"

document.write "<TD><B>Sun<TD><B>Mon<TD><B>Tue<TD><B>Wed<TD><B>Thu<TD><B>Fri<TD><B>Sat"

document.write "<TR>"

    firstdate=DateSerial(year(date), imonth, 1)

    thisdate=firstdate

    nextday=1

    For cday=1 to 7

        If WeekDay(thisdate)>cday Then

            document.write "<TD></TD>"

        else

            document.write "<TD ALIGN=CENTER><FONT SIZE=3>" & nextday & "</TD>"

            nextday=nextday+1

            thisdate=DateSerial(year(date), imonth, nextday)

        End If

    Next 

    document.write "<TR>"

    weekDays=1

    while month(thisdate)=imonth

        document.write "<TD ALIGN=CENTER><FONT SIZE=3>" & nextday & "</TD>"

        nextday=nextday+1

        weekDays=weekDays+1

        If weekDays>7 then

            WeekDays=1

            document.write "<TR>"

        End If

        thisdate=DateSerial(year(date), imonth, nextday)

    wend

document.write "</TABLE>"

document.write "</CENTER>"

document.close

End Sub

</SCRIPT>

</HEAD>

<BODY>

<FONT FACE="Comic Sans MS">

<CENTER>

<H1>Yearly Calendar</H1>

Click on a month to see a weekly calendar

<P>

<FONT FACE="Verdana" SIZE=6>

<TABLE CELLPADDING=10 BORDER>

<TR>

<COLGROUP>

<COL ALIGN=CENTER>

<COL ALIGN=CENTER>

<COL ALIGN=CENTER>



<TD><INPUT TYPE=BUTTON NAME="January" VALUE="JANUARY">

<TD><INPUT TYPE=BUTTON NAME="February" VALUE="FEBRUARY">

<TD><INPUT TYPE=BUTTON NAME="March" VALUE="MARCH">

<TR>

<TD><INPUT TYPE=BUTTON NAME="April" VALUE="APRIL">

<TD><INPUT TYPE=BUTTON NAME="May" VALUE="MAY">

<TD><INPUT TYPE=BUTTON NAME="June" VALUE="JUNE">

<TR>

<TD><INPUT TYPE=BUTTON NAME="July" VALUE="JULY">

<TD><INPUT TYPE=BUTTON NAME="August" VALUE="AUGUST">

<TD><INPUT TYPE=BUTTON NAME="September" VALUE="SEPTEMBER">

<TR>

<TD><INPUT TYPE=BUTTON NAME="October" VALUE="OCTOBER">

<TD><INPUT TYPE=BUTTON NAME="November" VALUE="NOVEMBER">

<TD><INPUT TYPE=BUTTON NAME="December" VALUE="DECEMBER">

</TABLE>

</BODY>

</HTML>

The 12 command buttons that correspond to the months of the year are placed on the page with straight HTML code. Each button's name corresponds to a month's name, and its onClick event handler displays the actual month calendar. The handler for the onClick event of the JANUARY button is


Sub JANUARY_onClick()

    DisplayMonth(1)

End Sub

The handlers of the other Click events are similar. They all call the DisplayMonth() subroutine with the proper arguments. The DisplayMonth() subroutine goes through the days of the specified month and prints them under the appropriate day column.

The program first displays the days of the week as headings. The next step is the display of the days of the first week with a For...Next loop. The first week in the month is usually incomplete and the first few cells in the table must remain blank. This loop goes through the seven days in the week until it hits the first day in the month, which happens when the weekday of the first day in the month is the same as the current cell. Until this happens, the program displays empty cells by writing the string <TD></TD> to the document. After the first day in the month is found, the program creates cells where it places the value of the variable nextday, which is increased with every iteration. The string that produces a cell with a number is:


"<TD ALIGN=CENTER><FONT SIZE=3>" & nextday & "</TD>"

This is HTML code, and any references to variables will be replaced with the actual variable value. If the value of the nextday variable is 24, the line that is written to the document is


<TD ALIGN=CENTER><FONT SIZE=3>24</TD>

which is straight HTML.

After the first week of the calendar has been displayed, the program continues with the following ones. These weeks are complete, except for the last one, of course.

The remaining days of the month are handled with a While...Wend loop. With each iteration, the nextday variable increases by one day, and the loop keeps going as long as you are in the same month (the condition while month(thisdate)=imonth). This loop makes use of an additional variable, the weekDays variable, which increases by one with each iteration and is reset back to 1 when it reaches 7. At the same time, the program inserts a <TR> tag to the output to start a new row in the table.

The code of the DisplayMonth() is fairly straightforward, and you can use it as a starting point for any application that needs to display a calendar. You can easily turn each day of the month into a hyperlink, pointing to a file on the server. If you maintain a separate document for each day of the month on the server, you can modify the application so that each day is a hyperlink to this date's file. Instead of writing the number of the day to the output, you could write a string that will turn it into a hyperlink. If you use the following string as the write method's argument:


"<A HREF=" & imonth & "-" & nextday & ".htm>" & nextday & "</A>"

the actual string that will be written to the output file is


<A HREF=1-21.htm>21</A>

which is indeed a hyperlink to the file 1-21.htm on the server. This file must reside on the same folder as the Calendar application, or you must prefix the filename with a relative pathname.

The history Object

The history object is an invisible object that provides methods for navigating through the document's history. It provides the functionality of the browser's navigational buttons, with the added benefit that you can access this functionality through programming. The following text explains the history object's methods.

Back n

Moves back in the history list by n steps, as if the user has clicked on the browser's Back button n times. To move to the most recently visited URL, use the statement


window.history.back 1

Forward n

Moves forward in the history list by n steps, as if the user has clicked on the browser's Forward button n times.

Go n

Moves to the nth item in the history list. The statement


window.history.go 1

will take you to the first URL in the list.

The history object also provides a property, the length property. This property represents the number of URLs in the history list. The current implementation of Internet Explorer always returns the number zero as the history list's length.

The HistoryObject Project

The HistoryObject document contains a floating frame and three command buttons, which enable you to control the contents of the floating frame. The first button enables the user to type the URL he or she wants to visit in an Input box; it then sets the frame's URL to the string entered by the user. The example uses a frame to display the various URLs, because if the window were updated using the write method, the new document would replace the original contents, including the command buttons. A frame makes it possible to provide the controls for manipulating the frame's URL via the history object's methods. You could also display the URL in a different window (see the open method of the window object), but this approach requires that the viewer moves back and forth between two windows.

You can enter a few URLs to visit manually. (Just remember to enter a fully qualified URL, including the protocol identifier, such as http://www.mcp.com/sams.) You can also follow the hyperlinks in the first URL, which appear when the project is opened for the first time. Then, you can test the Previous URL and Next URL buttons, which simply call the Back and Forward methods of the frame's history object. The document that produced the page in Figure 6.7 appears in the following code:


<HTML>

<HEAD>

<SCRIPT LANGUAGE=VBS>

Sub GoURL_onClick()

    newURL=InputBox("Enter the URL of the location you want to visit")

    Window.frames(0).location.href=newURL

End Sub



Sub NextURL_onClick()

    window.frames(0).history.forward 0

End Sub



Sub PreviousURL_onClick()

    window.frames(0).history.back 0

End Sub

</SCRIPT>

<CENTER>

<TABLE WIDTH=500>

<TR>

<TD ALIGN=CENTER><INPUT TYPE=BUTTON VALUE="Get me to this URL" NAME="GoURL" >

<TD ALIGN=CENTER><INPUT TYPE=BUTTON VALUE="   Previous URL   " NAME="PreviousURL" >

<TD ALIGN=CENTER><INPUT TYPE=BUTTON VALUE="     Next URL     " NAME="NextURL" >

</TABLE>

<P>

<IFRAME WIDTH=500 HEIGHT=400 NAME="MyFrame" SRC="http://www.microsoft.com">

</CENTER>

</HTML>

To display the URL entered in the Input box, the program assigns the string returned by the InputBox() function to the href property of the frame's location object. The other two buttons invoke the back and forward methods of the frame's history object.

When the page is first loaded, it connects to the Microsoft Web site, which appears in the frame. You can follow the hyperlinks of this document to switch to any other page within the same Web site or to visit another site. Some hyperlinks, however, cause the destination page to be displayed on the parent page (with the <A> tag's TARGET attribute), in effect removing your page from the browser's window. If this happens, the page with the command buttons will be replaced on the browser's window, and you must click on the browser's Back button to return to the LocationObject page, or click the Refresh button to reload the original page.

The navigator Object

This object, also invisible, returns information about the browser. You can access this information through the properties exposed by the navigator object, which are all read-only. An explanation of these properties appears in the following section:

appCodeName

Returns the code name of the application. Internet Explorer 3.0 returns Mozilla.

appName

Returns the name of the application. Internet Explorer 3.0 returns Microsoft Internet Explorer.

appVersion

Returns the version of the application. Internet Explorer 3.0 returns 2.0 (compatible; MSIE 3.0A; Windows 95).

userAgent

Returns the user agent of the application. Internet Explorer returns 2.0 (compatible; MSIE 3.0A; Windows 95).

The most practical use of the navigator object involves detecting whether the client is using Internet Explorer or another browser. Say that you have prepared an HTML page that can be viewed with any browser, and a more advanced version of the same page that makes use of floating frames and style sheets. These two features are currently supported by only Internet Explorer 3.0. You can easily detect which browser the client has running and display the appropriate page.

The BrowserInfo project you explore in the next section demonstrates the use of the navigator object's properties. The next example, NavigatorObject, shows you how to detect whether the browser used on the client is Internet Explorer and adjust the contents of the page accordingly.

The BrowserInfo Project

The BrowserInfo project demonstrates the properties of the navigator object. The BrowserInfo page, which you can find in this chapter's folder on the CD, contains a floating frame. This frame displays the Sams Web site and four command buttons with the four properties of the navigator object. Click the corresponding command button, and you see the values of the navigator object's properties, as reported by Internet Explorer. You should also open this project with other browsers to examine its behavior.

The code of the BrowserInfo page appears in the following text:


<HTML>

<HEAD>

<SCRIPT LANGUAGE=VBS>

Sub BrowserName_onClick()

    MsgBox window.navigator.AppName

End Sub



Sub BrowserCodeName_onClick()

    MsgBox window.navigator.AppCodeName

End Sub



Sub BrowserVersion_onClick()

    MsgBox window.navigator.AppVersion

End Sub



Sub BrowserAgent_onClick()

    MsgBox window.navigator.UserAgent

End Sub



</SCRIPT>



<CENTER>

<TABLE WIDTH=500>

<TR>

<TD><INPUT TYPE=BUTTON VALUE="Browser Name" NAME="BrowserName" >

<TD><INPUT TYPE=BUTTON VALUE="Browser Code" NAME="BrowserCodeName" >

<TD><INPUT TYPE=BUTTON VALUE="Browser Version" NAME="BrowserVersion" >

<TD><INPUT TYPE=BUTTON VALUE="Browser Agent" NAME="BrowserAgent" >

</TABLE>

<P>

<IFRAME WIDTH=550 HEIGHT=400 NAME="MyFrame" SRC="http://www.microsoft.com">

</CENTER>

</HTML>

The <IFRAME> tag inserts a so-called floating frame. A floating frame looks like a regular frame, but it can be placed anywhere on a page, like an image or any other HTML element. Floating frames are ideal for opening windows in a document, where other URLs can be displayed. In the previous listing, we placed a floating frame centered on the window and below the command buttons, where the Microsoft Web site is displayed. The document to be displayed in the floating frame is specified with the SRC attribute, which is similar to the <IMG> tag's attribute with the same name, only instead of an image, the <IFRAME> tag's SRC attribute specifies a Web site's URL.

The NavigatorObject Project

This example reads the browser's application name and uses it to decide whether to display a generic page or the same page enhanced with Internet Explorer 3.0 features. The NavigatorObject page, seen in Figure 6.6, contains the HTML description of the generic page and a few lines of VBScript code, which uses the navigator object's properties to detect the browser. The SCRIPT section of this page appears next:


<SCRIPT LANGUAGE=VBS>



If window.navigator.appname="Microsoft Internet Explorer" Then

    window.document.write "<CENTER>"

    window.document.write "<H1>A Web site in a floating frame</H1>"

    window.document.write "<IFRAME WIDTH=500 HEIGHT=400 NAME='MyFrame' SRC='http://

    www.mcp.com/sams'>"

    window.document.write "<\CENTER>"

End If



</SCRIPT>

If the browser can handle VBScript (if not, the browser probably can't handle floating frames and other Internet Explorer 3.0 specific features, either), it will execute the script and will display the page in a floating frame. If the browser doesn't recognize the SCRIPT section, or if it's not Internet Explorer, nothing will happen, and in effect, the entire script will be ignored. The following text shows the entire HTML document, which consists of a SCRIPT section that displays the Sams Web site in a floating frame, and the HTML description of the generic page that prompts the user to download Internet Explorer:


<HTML>

<HEAD>

<SCRIPT LANGUAGE=VBS>

If window.navigator.appname="Microsoft Internet Explorer" Then

    window.document.write "<CENTER>"

    window.document.write "<H1>A Web site in a floating frame</H1>"

    window.document.write "<IFRAME WIDTH=500 HEIGHT=400 NAME='MyFrame' SRC='http://

    www.mcp.com/sams'>"

    window.document.write "<\CENTER>"

End If

</SCRIPT>

<CENTER>

<H1>This site is optimized for Internet Explorer 3.0</H1>

<P>

Click <A HREF="www.microsoft.com/ie">here</A> to download the browser.

<A HREF="http://www.microsoft.com/usa/ie/rm/supernet.htm"><IMG BORDER="0" SRC="ie_animated.gif" WIDTH="88" HEIGHT="31" VSPACE="7" ALT="Microsoft Internet Explorer" 
></A><BR>

</CENTER>

</HTML>

Figure 6.6 : If you view the NavigatorObject with Internet Explorer 3.0, the page displays a Web site in a floating frame.

The generic page used in this example, shown in Figure 6.7, is too generic. It doesn't display any actual content; it just prompts the viewer to download Internet Explorer and provides a link to the download site. You can open this project with other browsers to see how it works. The code for this example has a small bug; namely, it doesn't distinguish between versions 2.0 and 3.0 of Internet Explorer. Internet Explorer 2.0, for example, doesn't support frames. If you anticipate that some of your viewers still use Internet Explorer 2.0, you must also check the version of the browser from within your application to make sure it will not attempt to display floating frames using Internet Explorer 2.0.

Figure 6.7 : If the NavigatorObject page is opened with a browser other than Internet Explorer, it displays this generic page.

The location Object

The location object provides information about the window's current URL. You have already seen examples of the location object, but all of its properties have not been discussed. This section provides the complete list of the properties of the location object.

href

Returns or sets the compete URL for the location to be loaded into the browser's window. Use this property to connect to another location through your VBScript code.

To find out the current document's URL, use a statement such as this one:


MsgBox "You are currently viewing " & document.location.href

You can also cause another document to appear on the window, or a frame, with the statement:


document.location.href="http://www.microsoft.com"

The following properties set the various parts of the URL:

protocol

Returns or sets the protocol of the URL (usually http).

host

Returns or sets the host and port of the URL. The host and port are separated with a colon, as in host:port.

hostname

Reads or sets the host of a URL, which can be either a name or an IP address.

port

Returns or sets the port of the URL (you rarely have to specify the port number in a WWW URL).

pathname

Returns or sets the pathname of the URL. Use this property when you want to specify a document, other than the Web's root document, to be displayed.

search

Returns or sets the search portion of the URL, if it exists. The search portion of the URL is the string that follows the question mark in the URL when the browser submits data to the server. If the URL is


http://www.someServer.com/cgi/RegisterUser.exe?UName="Peter Evans"

the search portion of this URL is UName="Peter Evans". If the URL doesn't contain a search portion, the search property is an empty string.

hash

Returns or sets the hash portion of the URL.

The LocationObject Project

The LocationObject page on the CD demonstrates the location object's properties. The page LocationObject has a structure similar to that of the previous examples. It contains a floating frame and a few command buttons that demonstrate the properties of the location object. The floating frame of the page shown is a container into which any HTML can be loaded and displayed. To display a new page in the floating frame, the user must click the Get me to this URL button and is prompted to enter the desired URL. The program expects the full name of the URL, including the protocol identifier. The URL of the page is http://www.mcp.com/sams.

The second command button displays the URL of the document in the floating frame in a message box. Finally, the Location Properties button displays several of the location's properties in a message box, as shown in Figure 6.8. Notice that the root document on a Web site doesn't have a pathname property. For the pathname property to have a value, you must follow a hyperlink to another document.

Figure 6.8 : The location properties of a page on the Sams Web site as displayed from within the LocationObject page.

The actual code of the LocationObject page appears next:


<HTML>

<HEAD>

<SCRIPT LANGUAGE=VBS>

Sub GoURL_onClick()

    newURL=InputBox("Enter the URL of the location you want visit")

    Window.frames(0).location.href=newURL

End Sub



Sub ShowURL_onClick()

    MsgBox "You are currently viewing the URL " & Window.Frames(0).location.href

End Sub



Sub LocationProps_onClick()

    str="PROTOCOL " & Window.Frames(0).location.protocol

    str=str+chr(10)+"HOST     " & Window.Frames(0).location.host

    str=str+chr(10)+"HOSTNAME " & Window.Frames(0).location.hostname

    str=str+chr(10)+"PORT     " & Window.Frames(0).location.port

    str=str+chr(10)+"PATHNAME " & Window.Frames(0).location.pathname

    str=str+chr(10)+"SEARCH   " & Window.Frames(0).location.search

    MsgBox str

End Sub

</SCRIPT>



<CENTER>

<TABLE WIDTH=500>

<TR>

<TD><INPUT TYPE=BUTTON VALUE="Get me to this URL" NAME="GoURL" >

<TD><INPUT TYPE=BUTTON VALUE="Show me this URL" NAME="ShowURL" >

<TD><INPUT TYPE=BUTTON VALUE="Location Properties" NAME="LocationProps" >

</TABLE>

<P>

<IFRAME WIDTH=500 HEIGHT=400 NAME="MyFrame" SRC="http://www.microsoft.com">

</CENTER>

</HTML>

The code behind the GoURL button sets the href property of the location object of the window's first frame. The code of the ShowURL button reads this property and displays it in a message box. The code behind the third button's click event becomes lengthier, as it creates step by step the string with all the properties of the location object before displaying them in the message box. chr(10) is the new-line character and is used to cause each new property to appear on a separate line.

The link Object

Another invisible object, the link object, represents a link in an HTML document and exposes various properties through which you can find out the destination of the link. The basic property of the link object is the length property, which returns the number of the links in the document. Each link is a member of the links array. The first link is links(0), the second one is links(1), and so on. Because the hyperlinks in a document are destinations, the link object's properties are identical to the properties of the location object; however, they are read-only this time. A brief explanation of each property follows, but for a more detailed discussion of these properties, see the "The location Object" section.

href

Returns or sets the compete URL for the location to be loaded into the frame.

protocol

Returns or sets the protocol of the URL (usually HTTP).

host

Returns or sets the host and port of the URL.

hostname

Reads or sets the host of a URL, which can be either a name or an IP address.

port

Returns or sets the port of the URL.

pathname

Returns or sets the pathname of the URL.

search

Returns or sets the search portion of the URL, if it exists.

hash

Returns or sets the hash portion of the URL.

target

The last property of the frames object is the target that may have been specified in the <A> frame. The target of the link is the window, or frame, where the destination document will appear.

The LinksObject Project

The LinksObject document demonstrates the use of the link object and the links array. The LinksObject page contains a floating frame, where a user-supplied URL appears, and a number of command buttons. The first three command buttons are navigational (you have seen the code behind those buttons in the previous examples of this chapter), and the other three manipulate the links and anchors arrays. The Count Hyperlinks button displays the number of hyperlinks and anchors in the document displayed in the floating frame. The other two buttons display, on a new page, all the hyperlinks and anchors on the current document, respectively.

The hyperlinks and anchors of the document appear on the same page as the LinksObject document, in effect replacing the original document.

Instead of repeating the code of the entire document, the text shows only the subroutines that count the hyperlinks and display the list of hyperlinks and anchors. The CountLinks() subroutine uses the length property of the links object to get the number of hyperlinks in the document and the length property of the anchor object to get the number of anchors. Then, it combines them in a string which is displayed with the MsgBox() function:


Sub CountLinks_onClick()

    str="This document contains" & chr(10)

    str=str & window.frames(0).document.Links.Length & " links and" & chr(10)

    str=str & window.frames(0).document.Anchors.Length & " anchors"

    MsgBox str

End Sub

The ShowLinks() and ShowAnchors() subroutines open a new document on the same window and write the elements of the links and anchors arrays, respectively, there. Notice that the links are placed on the document as hyperlinks so that you can also follow them from this page.


Sub ShowLinks_onClick()

    Document.clear

    Document.open

    For i=0 to window.frames(0).document.Links.Length-1

        Document.write "<A HREF=" & window.frames(0).document.Links(i).href & ">" & window.frames(0).document.links(i).href & "</A><BR>"

    Next

    Document.Close

End Sub



Sub ShowAnchors_onClick()

    Document.open

    For i=0 to window.frames(0).Document.Anchors.Length-1

        Document.write window.frames(0).Document.Anchors(i)

    Next

    Document.Close

End Sub

To return to the previous window, you must click the browser's Refresh button. The Back button won't work because no previous document is in use. It's the same document! When you use the write method to send output to the current window, you're not creating a new page, you just change the contents of the page that contains the script dynamically.

Review

The Internet Explorer scripting object model is a collection of objects through which you can control Internet Explorer and the HTML documents displayed in it programmatically. As demonstrated in several examples in this chapter, it is even possible to create the content to be displayed on the fly, with the methods of certain objects of the scripting model (in particular, the document object, which is the flexible one).

The scripting model is a hierarchy of objects, each one of which exposes certain properties and methods. Some of the properties are objects, and they can apply to more than one object. The document object, for instance, is a property of the window object and represents the document currently displayed in the window. If the current document contains frames, each frame has a document property as well, which represents the document of the individual frame.

The document object provides the write method, which lets you control the actual contents of the document from within your script. When the document object is used as a property of the window object, the write method applies to the document displayed on the window, regardless of whether or not it contains frames. When the document object is used as a property of a frame, the write method applies to the specific frame.

The objects of the scripting model are arranged in a hierarchy that reflects their function and their role in scripting. The topmost object in this hierarchy is the window object, which is the container for HTML documents, forms and scripts. Most of the window's properties are objects, too, such as the frames object (a collection of all the frames in the current document, if any), the history object (an object that exposes the navigational methods, such as Back and Forward), the location object (which lets you connect to any URL via its href property), and so on. The document object is the most flexible object in the hierarchy, in the sense that it allows you, the programmer, to generate HTML pages on the fly, based on conditions such as user preferences, dates, or the browser used to display the page on the client.