Schongar P.VBScript unleashed.1997
.pdfMsgBox "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))
