Java Reference
In-Depth Information
You could write this with the same, exact results:
window.alert("Hello!");
However, because the
window
object is the global object, it is perfectly correct to use the first version.
Some of the properties of the
window
object are themselves objects. Those common to all browsers
include the
document
,
navigator
,
history
,
screen
, and
location
objects. The
document
object
represents your page, the
history
object contains the history of pages visited by the user, the
navigator
object holds information about the browser, the
screen
object contains information
about the display capabilities of the client, and the
location
object contains details on the current
page's location. You look at these important objects individually later in the chapter.
At this point it's worth highlighting the fact that, within a web page, you shouldn't use names
for your functions or variables that conflict with names of BOM objects or their properties and
methods. If you do, you may not get an error, but instead get unexpected results. For example, the
following code declares a variable named
history
, and tries to use the
history
property of the
window
object to go back to the previous page. This, however, won't work because
history
has
been changed to hold a different value:
var history = "Hello, BOM!";
window.history.back(); // error; string objects don't have a back() method
In this situation you need to use a different variable name. This happens because any function or
variable you define within the global scope actually gets appended to the
window
object. Look at
this code as an example:
var myVariable = "Hello, World!";
alert(window.myVariable);
If you were to execute this code in a browser, the alert window would display the message “Hello,
World.”
As with all the BOM objects, you can look at lots of properties and methods for the
window
object.
However, in this chapter you concentrate on the
history
,
location
,
navigator
,
screen
, and
document
properties. All five of these properties contain objects (the
history
,
location
,
navigator
,
screen
, and
document
objects), each with its own properties and methods. In the next few pages, you
look at each of these objects in turn and find out how they can help you make full use of the BOM.
the history object
The
history
object keeps track of each page that the user visits. This list of pages is commonly
called the
history stack
for the browser. It enables the user to click the browser's Back and Forward
buttons to revisit pages. You have access to this object via the
window
object's
history
property.
Like the native JavaScript
Array
type, the
history
object has a
length
property. You can use this
to find out how many pages are in the history stack.
As you might expect, the
history
object has the
back()
and
forward()
methods. When they are
called, the location of the page currently loaded in the browser is changed to the previous or next
page that the user has visited.