Tải bản đầy đủ (.pdf) (30 trang)

Windows and Frames

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (321.08 KB, 30 trang )

Chapter 13. Windows and Frames
Chapter 12 described the Window object and the central role it plays in client-side
JavaScript. We've seen that the Window object serves as the global object for client-side
JavaScript programs, and, as illustrated in Figure 12-1, it is also the root of the client-side
object hierarchy.
Besides
Every web browser window and every frame within every window is represented by a
Window object. The Window object defines quite a few properties and methods that are
important in client-side JavaScript programming. This chapter explores those properties
and methods and demonstrates some important techniques for programming with
windows and frames. Note that because the Window object is so central to client-side
program is quite long. Don't feel you have to master all this material at
once -- you may find it easier to study this chapter in several shorter chunks!
verview
We beg
and me
more detail. As usual, the client-side reference section contains complete coverage of
Window object properties and methods.
The most important properties of the Window object are the following:
A boolean value that is only if the window has been closed.
defaultStatus, status
ext that appears in the status line of the browser.
docum
that represents the HTML document
e Document object is covered in detail in Chapter 14
these special roles, the Window object is an important object in its own right.
ming, this chapter
13.1 Window O
in this chapter with an overview of some of the most commonly used properties
thods of the Window object. Later sections of the chapter explain this material in
closed


true
The t
ent
A reference to the Document object
displayed in the window. Th .
frames[]
that represent the frames (if any) within the window.An array of Window objects
history
resents the user's browsing history for
location
represents the URL of the document
t property causes the browser to load a new
name
The name of the window. Can be used with the target attribute of the HTML
<a> tag, for example.
parent
If the current window is a frame, a reference to the frame of the window that
contains it.
self
A self-referential property; a reference to the current Window object. A synonym
for
window.
top
If the current window is a frame, a reference to the Window object of the top-
level window that contains the frame. Note that top is different from parent for
frames nested within other frames.
window
A reference to the History object that rep
the window.
A reference to the Location object that

displayed in he window. Setting this
document.
opener
A reference to the Window object that opened this one, or null if this window
was opened by the user.
A self-referential property; a reference to the current Window object. A synonym
for self.
The Window object also supports a number of important methods:
alert( ) , confirm( ), prompt( )
Display simple dialog boxes to the user and, for confirm( ) and prompt( ), get
the user's response.
close( )
Close the window.
focus( ) , blur( )
Request or relinquish keyboard focus for the window. The focus( ) method also
ensures that the window is visible by bringing it to the front of the stacking order.
moveBy( ) , moveTo( )
Move the window.
open( )
Open a new top-level window to display a specified URL with a specified set of
features.
print( )
Print the window or frame -- same as if the user had selected the Print button
from the window's toolbar (Netscape 4 and later and IE 5 and later only).
resizeBy( ) , resizeTo( )
Resize the window.
scrollBy( ) , scrollTo( )
Scroll the document displayed within the window.
y
between invocations.

ut( )
milliseconds.
.2 Simple Dialog Boxes
Three commonly used Window methods are alert( ) , confirm( ), and prompt( ).
ed
setInterval( ) , clearInterval( )
Schedule or cancel a function to be repeatedly invoked with a specified dela
setTimeout( ) , clearTimeo
Schedule or cancel a function to be invoked once after a specified number of
As you can see from these lists, the Window object provides quite a bit of functionality.
The remainder of this chapter explores much of that functionality in more detail.
13
These methods pop up simple dialog boxes. alert( ) displays a message to the user,
confirm( ) asks the user to click an Ok or Cancel button to confirm or cancel an
boxes producoperation, and prompt( ) asks the user to enter a string. Sample dialog
by these three methods are shown in Figure 13-1.
Figure 13-1. alert( ), confirm( ), and prompt( ) dialog boxes
Note that the text displayed by these dialog boxes is plain text, not HTM
format these dialog boxes only with spaces, newlines, and vari
L-formatted text.
You can ous punctuation
characters. Adjusting the layout generally requires trial and error. Bear in mind, though,
that the dialog boxes look different on different platforms and in different browsers, so
you can't always count on your formatting to look right on all possible browsers.
Some browsers (such as Netscape 3 and 4) display the word "JavaScript" in the titlebar or
upper-left corner of all dialog boxes produced by
alert( ), confirm( ), and prompt(
)
. Although designers find this annoying, it should be considered a feature instead of a
bug: it is there to make the origin of the dialog box clear to users and to prevent you from

writing Trojan-horse code that spoofs system dialog boxes and tricks users into entering
their passwords or doing other things that they shouldn't do.
The
confirm( ) and prompt( ) methods block -- that is, those methods do not return
until the user dismisses the dialog boxes they display. This means that when you pop up
one of these boxes, your code stops running and the currently loading document, if any,
stops loading until the user responds with the requested input. There is no alternative to
blocking for these methods -- their return value is the user's input, so they must wait for
the user before they can return. In most browsers, the alert( ) method also blocks and
waits for the user to dismiss the dialog box. In some browsers, however (notably
Netscape 3 and 4 on Unix platforms), alert( ) does not block. In practice, this minor
incompatibility rarely causes problems.
Example 13-1 shows some typical uses of these methods.
Example 13-1. Using the alert( ), confirm( ), and prompt( ) methods
n will take some time and that the user should
// be patient. It would be suitable for use in the onsubmit event
s.
arn_on_submit( )
{
alert("\n_________________________________________________ _\n\n"
+
" Your query is being submitted...\n" +
"_________________________________________________ _\n\n"
+
"Please be aware that complex queries such as yours\n" +
" can require a minute or more of search time.\n\n" +
" Please be patient.");
}
// Here is a use of the confirm( ) method to ask if the user really
// wants to visit a web page that takes a long time to download. Note

that
// the return value of the method indicates the user response. Based
// on this response, we reroute the browser to an appropriate page.
var msg = "\nYou are about to experience the most\n\n" +
" -=| AWESOME |=-\n\n" +
"web page you have ever visited!!!!!!\n\n" +
"This page takes an average of 15 minutes to\n" +
"download over a 56K modem connection.\n\n" +
"Are you ready for a *good* time, Dude????";
if (confirm(msg))
location.replace("awesome_page.html");
else
location.replace("lame_page.html");
rs typically display a status line at the bottom of every window (except for
messages to the user.
n the user moves the mouse over a
imple context help message that
// Here's a function that uses the alert( ) method to tell the user
// that form submissio
handler
// of an HTML form.
// Note that all formatting is done with spaces, newlines, and
underscore
function w
// Here's some very simple code that uses the prompt( ) method to get
// a user's name and then uses that name in dynamically generated HTML.
n = prompt("What is your name?", "");
document.write("<hr><h1>Welcome to my home page, " + n + "</h1><hr>");
13.3 The Status Line
Web browse

those explicitly created without one), where the browser can display
When the user moves the mouse over a hypertext link, for example, the browser usually
displays the URL to which the link points. And whe
wser control button, the browser may display a sbro
explains the purpose of the button. You can also make use of this status line in your own
eb browsers usually display the URL of a hypertext link when the user passes
ehave
ed
f
ote that the event handler *must* return true for this to work. -
<map name="map1">
n Center'; return true;">
oords="0,20,50,40" href="order.html"
<area coords="0,40,50,60" href="help.html"
onmouseover="status='Get help fast!'; return true;">
r
true
handler displays in the status line with its own URL.
Don't worry if you do not fully understand the event handler in this example. We'll
explain events in
Chapter 19
programs. Its contents are controlled by two properties of the Window object: status
and defaultStatus.
Although w
the mouse pointer over the link, you may have encountered some links that don't b
this way -- links that display some text other than the link's URL. This effect is achiev
with the status property of the Window object and the onmouseover event handler o
hypertext links:
<!-- Here's how you set the status line in a hyperlink.
-- N

->
Lost? Dazed and confused? Visit the
<a href="sitemap.html" onmouseover="status='Go to Site Map'; return
ue;">tr
Site Map
</a>
<!-- You can do the same thing for client-side image maps -->
<img src="images/imgmap1.gif" usemap="#map1">
<area coords="0,0,50,20" href="info.html"
useover="status='Visit our Informatio onmo
<area c
onmouseover="status='Place an order'; return true;">
</map>
The onmouseover event handler in this example must return true. This tells the browse
that it should not perform its own default action for the event -- that is, it should not
display the URL of the link in the status line. If you forget to return , the browser
overwrites whatever message the
.
L
w status property --
your custom message is displayed while the mouse is over the hyperlink and is erased
when the mouse moves off the link.
The status property is intended for exactly the sort of transient message we saw in the
previous example. Sometimes, though, you want to display a message that is not so
transient in the status line -- for example, you might display a welcome message to users
visiting your web page or a simple line of help text for novice visitors. To do this, you set
the
defaultStatus property of the Window object; this property specifies the default
text displayed in the status line. That text is temporarily replaced with URLs, context help
When the user moves the mouse pointer over a hyperlink, the browser displays the UR

for the link, then erases the URL when the mouse moves off the hyperlink. The same is
true when you use an
onmouseover event handler to set the Windo
messages, or other transient text when the mouse pointer is over hyperlinks or br
control buttons, but once the mouse moves off those areas, the default text is restored.
You might use the defaultStatus property like this to provide a friendly and helpful
message to real beginners:
<script>
owser
defaultStatus = "Welcome! Click on underlined blue text to navigate.";
13.4 Timeouts and Intervals
The setTimeout( ) method of the Window object schedules a piece of JavaScript code
to be run at some specified time in the future. The clearTimeout( ) method can be used
to cancel the execution of that code. setTimeout( ) is commonly used to perform
animations or other kinds of repetitive actions. If a function runs and then uses
The setTimeout( ) method is commonly used in conjunction with the status or
defaultStatus properties to animate some kind of message in the status bar of the
browser. In general, animations involving the status bar are gaudy, and you should shun
n
</script>
setTimeout( ) to schedule itself to be called again, we get a process that repeats
without any user intervention. JavaScript 1.2 has added the setInterval( ) and
clearInterval( ) methods, which are like setTimeout( ) and clearTimeout( ),
except that they automatically reschedule the code to run repeatedly; there is no need for
the code to reschedule itself.
them! There are, however, a few status-bar animation techniques that can be useful and i
good taste. Example 13-2 shows such a tasteful status-bar animation. It displays the
current time in the status bar and updates that time once a minute. Because the update
occurs only once a minute, this animation does not produce a constant flickering
distraction at the bottom of the browser window, like so many others do.

Note the use of the onload event handler of the <body> tag to perform the first call to the
display_time_in_status_line( ) method. This event handler is invoked once when
the HTML document is fully loaded into the browser. After this first call, the method
uses to schedule itself to be called every 60 seconds so that it can update
d time.
Examp us line
<html>
<head>
ion displays the time in the status line
// Invoke it once to activate the clock; it will call itself from then
on
functi
{
setTimeout( )
the displaye
le 13-2. A digital clock in the stat
<script>
// This funct
on display_time_in_status_line( )
va
var h = d.getHours( ); // Extract hours: 0 to 23
var m = d.getMinutes( ); // Extract minutes: 0 to 59
va
if (h > 12) h -= 12; // Convert 24-hour format to
12-hour
if (h == 0) h = 12; // Convert 0 o'clock to
midnight
if
minute
va

defaultStatus = t; // Display it in the status
// Arrange to do it all again in one minute
setTimeout("display_time_in_status_line( )", 60000); // 60000 ms
is one
}
</script>
bother starting the clock till everything is loaded. The
anyway
<body
<!-- The HTML document contents go here -->
</body>
In JavaScript 1.2, Example 13-2
r d = new Date( ); // Get the current time
r ampm = (h >= 12)?"PM":"AM"; // Is it a.m. or p.m.?
(m < 10) m = "0" + m; // Convert 0 minutes to 00
s, etc.
r t = h + ':' + m + ' ' + ampm; // Put it all together
line
minute
</head>
<!-- Don't
-- status line will be busy with other messages during loading,
. -->
onload="display_time_in_status_line( );">
</html>
could be written using setInterval( ) instead of
the
event
handler. Instead, after defining display_time_in_status_line( ), our script would
call setInterval( ) to schedule an invocation of the function that automatically repeats

once every 60,000 milliseconds.
13.5 Error Handling
The onerror property of a Window object is special. If you assign a function to this
property, the function will be invoked whenever a JavaScript error occurs in that window:
the function you assign becomes an error handler for the window.
Three arguments are passed to an error handler. The first is a message describing the
error that occurred. This may be something like "missing operator in expression", "self is
read-only", or "myname is not defined". The second argument is a string that contains the
URL of the document containing the JavaScript code that caused the error. The third
argument is the line number within the document where the error occurred. An error
handler can use these arguments for any purpose it desires. A typical error handler might
display the error message to the user, log it somewhere, or force the error to be ignored.
setTimeout( ) setTimeout( ) call would be removed from
splay_time_in_status_line( ) method, and we'd remove the onload
. In this case, the
di
In addition to those three arguments, the return value of the onerror handler is
significant. Browsers typically display an error message in a dialog box or in the status
line when an error occurs. If the onerror handler returns true, it tells the system that the
h necessary -- in other words, the
system should not display its own error message. For example, if you do not want your
users to be pestered by error messages, no matter how buggy the code you write is, you
ke this at the start of all your JavaScript programs:
very difficult for users to give you feedback when your
ing error messages.
onerror handler in Example 14-1
andler has handled the error and that no further action is
could use a line of code li
self.onerror = function( ) { return true; }
Of course, doing this will make it

programs fail silently without produc
We'll see a sample use of an . That example uses the
handler to display the error details to the use w the user to submit a bug
Note that the onerror error handler
port JavaScript 1.5 have
an alternative means of catching and handling errors, however: they can use the
onerror r and allo
report containing those details.
is buggy in Netscape 6. Although the function you
specify is triggered when an error occurs, the three arguments that are passed are
other browsers that supincorrect and unusable. Netscape 6 and
try/catch statement. (See Chapter 6 for details.)
13.6 The Navigator Object
The Window.navigator property refers to a Navigator object that contains information
about the web browser as a whole, such as the version and a list of the data formats it can
display. The Navigator object is named after Netscape Navigator, but it is also supported
by Internet Explorer. IE also supports clientInformation as a vendor-neutral synonym
for navigator. Unfortunately, Netscape and Mozilla do not support this property.
The Navigator object has five main properties that provide version information about the
browser that is running:
appName
The simple name of the web browser.
appVersion
The version number and/or other version information for the browser. Note that
this should be considered an "internal" version number, since it does not always
correspond to the version number displayed to the user. For example, Netscape 6
reports a version number of 5.0, since there never was a Netscape 5 release. Also,
IE Versions 4 through 6 all report a version number of 4.0, to indicate
fourth-generation browsers.
appCodeName

The code name of the browser. Netscape uses the code name "Mozilla" as the
value of this property. For compatibility, IE does the same thing.
platform
The hardware platform on which the browser is running. This property was added
in JavaScript 1.2.
The following lines of JavaScript code display each of these Navigator object properties
in a dialog box:
var browser = "BROWSER INFORMATION:\n";
for(var propname in navigator) {
browser += propname + ": " + navigator[propname] + "\n"
}
alert(browser);
compatibility with the baseline functionality of
userAgent
The string that the browser sends in its USER-AGENT HTTP header. This property
typically contains all the information in both appName and appVersion.
Figure 13-2 shows the dialog box displayed when the code is run on IE 6.
Figure 13-2. Navigator object properties
As you can see from Figure 13-2, the properties of the Navigator object have values that
are sometimes more complex than we are interested in. We are often interested in only
the first digit of the appVersion property, for example. When using the Navigator object
to test browser information, we often use methods such as parseInt( ) and
want. Example 13-3String.indexOf( ) to extract only the information we shows some
tor object and stores them in
an object named browser. These properties, in their processed form, are easier to use
than the raw navigator properties. The general term for code like this is a "client
code that does this: it processes the properties of the Naviga
sniffer," and you can find more complex and general-purpose sniffer code on the
Internet.
[1]

For many purposes, however, something as simple as that shown in Example
13-3 works just fine.
[1]
See, for example, />Example 13-3. Determining browser vendor and version
/*
ript SRC="browser.js"></script>
*
* A simple "sniffer" that determines browser version and vendor.
* It creates an object named "browser" that is easier to use than
* the "navigator" object.
*/
// Create the browser object
var browser = new Object( );
// Figure out the browser's major version
browser.version = parseInt(navigator.appVersion);
// Now figure out if the browser is from one of the two
// major browser vendors. Start by assuming it is not.
browser.isNetscape = false;
browser.isMicrosoft = false;
* File: browser.js
* Include with: <sc

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×