Section A. The window object


A. The window object

At the center of the BOM stands the window object. It serves four purposes:

  • It is the global object that JavaScript Core needs to function.

  • It represents the browser window that users see on their computer screen.

  • It grants access to the HTML document loaded in the window.

  • It contains miscellaneous information and functionality.

As JavaScript's global object, the window object contains all the variables and functions defined in your scripts. (We discussed the global object in 5J.)

As a representation of the browser window, the window object holds methods like resizeTo that allow you to change the window's dimensions, and objects such as screen that give information about the user's computer screen. In addition, it allows you to open and close new browser windows.

As the access portal to the HTML document, the window holds the document object, which in turn holds the entire HTML page the user is currently viewing.

Finally, as a holder of miscellaneous information and functionality, the window object contains the location and history objects, which are meant for navigation, a few interaction methods such as alert, and the browser's userAgent string.

The window as global object

As we saw in 5J, JavaScript always creates a global object to hold all global variables and functions in your scripts. If you wish, you can explicitly invoke this global object, for instance:

var test = 'Hello world'; alert(window.test); 


test is a global variable, and as such it's a property of the window object. Therefore window.test also accesses the variable.

Every browser window or frame is a global object in its own right. Although communication between these global objects is possible in certain circumstances, they remain separate.

New pages, new window object

In the course of a browsing session, one window object can contain many pages. Whenever the user loads a new page, the old page is thrown away and the new one is loaded into the same window object.

When that happens, JavaScript's global object is also cleaned rigorously. All variables and functions are destroyed, and if you still need them in the new page you have to redefine them by rerunning your initialization script and other functions.

Persistent window object

When the user loads a new page in a window, or even when he closes the entire window, the window object is wiped clean but is not destroyed. The most important consequence of this persistence of the window object is that any reference to it remains in force.

For example, when you open a popup, the browser creates an opener property in the popup that refers to the window it's opened from. This is an automatic, and very useful, feature that we'll discuss in detail in 6B.

When the user loads a new page in the main window, the window object is wiped clean. It is not destroyed, however, and therefore the opener property of the popup still refers to the same window object as it did earlier. (Of course, if the window now contains a page from another domain, JavaScript's same-source policy does not allow you to access this page. We'll get back to this problem in 6B.)

Even when the user closes the main window, opener still refers to the now-closed window. The window is gone from the computer's screen, but the window object still exists and can still be accessed, even though it doesn't contain any useful data any more.

I use this fact extensively in Site Survey, and we'll discuss it in more detail in 6B, when we treat cross-window communication.

Persistent data

Sometimes a page contains bits of data that you want to keep for future use, even when the page is removed. Suppose a page contains a module that calculates the user's yearly spending on insurance. In another page, you want to use the result of these calculations to show the user why it's advisable to insure herself with the company.

The result of the calculation is likely held by a global variable in the first page, and as soon as the user loads the second page, this global variable is lost. Somehow, you have to transfer the result of the calculation in the first page to the second page. You have to do this manually; there is no automatic way of taking care of it.

You have three options. You can store the data in a cookie. You can store the data in another window object. The new page can then retrieve the data from either of these sources. We'll treat these two scenarios in this chapter (6B and 6G, respectively).

The third option is that you send the data to the server for safekeeping. This is the most secure solution, since both cookies and other window objects can go astray and you run the risk of losing the result of the calculation. Nonetheless, sending data to the server is usually more complicated than storing it in a cookie or another window. It generally involves a form and a server-side script that catches and stores the data, and retrieves it later on.

In short, storing the data on the server is the safest solution, but it requires a bit of extra work. In Site Survey, I opted for storing some data in a cookie, and other data in another window.

New windows as new global objects

Your Web site may have more than one window, and thus more than one global object. If you use popups or frames, you effectively create several window objects, each of which is completely separate from all the others. These window objects are all global objects, and can contain variables or functions with the same names.

Suppose your site uses a main window and a popup, and suppose you define a variable message in each of them:

var message = 'Hello world'; // in main window var message = 'Goodbye, cruel world'; // in popup window 


These two variables message are completely independent, since they're properties of different global objects. If you add a line alert(message), it shows 'Hello world' in the main window, and 'Goodbye, cruel world' in the popup window. Both alert statements use the value of message as defined in their own global object.

Sometimes you need variables or functions from another window, as I do in Site Survey. In order to access them, you first have to access the other window (or rather, the other global object). Once you've done that, you can request its properties and methods, which are its variables and functions. For instance, this alerts "Goodbye, cruel world" in the main window:

// in main window var popup = [open popup and create reference to its window object]; alert(popup.message); 


Using variables and functions that are defined in another window is therefore not very difficult, provided you can access the other window. As we'll see in 6B, gaining access to other windows is the most serious problem.

Availability of variables in other windows

But there's a catch we have to discuss right away. The last example, though correct in theory, does not work in practice:

// in main window var popup = [open popup and create reference to its window object]; alert(popup.message); 


The second line correctly accesses the message property of the popup global object. Nonetheless, it'll likely give a JavaScript error.

The problem is that the popup is created in the first line of code, and the browser hasn't had the time yet to download the page. When the second line is executed, message is not yet available, and the second line results in a JavaScript error.

This problem also exists in Site Survey. The page in the main window calls a function in the popup when it is unloaded; i.e., when the user requests another page or closes the window. This popup is opened as soon as the user clicks anywhere in the main window. (Why? To defeat popup blockers. See 6B.)

These two things might happen simultaneously. In fact, it's quite likely that the user's first click takes place on a link. In that case, the click event causes the popup to be created, and immediately afterwards the main page unloads, which triggers the function call to the popup. Unfortunately, at that moment in time, the function is not yet available, since the HTML page for the popup hasn't yet been downloaded from the server. Without some extra safeguards, this routine would give a JavaScript error.

The solution is a careful bit of checking and the creation of several cookies to hold window statuses. (We'll discuss cookies fully in 6G.) This is the function that's executed when the main window unloads:

[Site Survey/survey.js, lines 66-73, condensed]

// in main window function ST_exit() {    if (readCookie('ST_popup') == 'opened' && ST_newWindow)           ST_newWindow.trackMain(location.href);    else           createCookie('ST_temp_store',location.href,1); } 


The script wants to execute the function trackMain() in the popup. It first checks if the popup has been opened by seeing if the ST_popup cookie exists. Then the script checks if the ST_newWindow variable, which should refer to the popup, has a value. If it does, the popup can be safely accessed and it calls trackMain().

If the popup creation takes place just before the main window is unloaded, the popup page isn't available yet, the cookie and the ST_newWindow variables don't yet exist, and the script goes to the else clause: it creates a cookie ST_temp_store that temporarily stores the page's URL (location.href).

When the popup page has been completely loaded, the script does the following:

[Site Survey/popup.js, lines 4-11]

// in popup window.onload = function () {    createCookie('ST_popup','opened',1);    if (readCookie('ST_temp_store')) {           trackMain(readCookie('ST_temp_store'));           eraseCookie('ST_temp_store');    } } 


First it creates the cookie ST_popup, so that the scripts in the main window know that the popup is available. Next, it sees if there's a cookie ST_temp_store. If there is, it calls trackMain() to handle it, and erases the cookie.

Window properties

Every window object has a few miscellaneous properties.

window and self

The window and self properties refer to the window itself. Therefore, window.innerWidth accesses the innerWidth property of the window object, and self.innerWidth accesses the same property. I have no idea why we need two properties that refer to the same object.

name

The name property serves as a guide for the target property of HTML links, and also for popups. Initially it's empty, but you can always set it. Take this code:

window.name = 'ppk'; 


Window and Self Traditions

As you'll see throughout this chapter, I sometimes use window and sometimes use self to refer to the window. Although it doesn't matter which property you use, it is traditional to say window.open() but self.innerWidth. I suspect that these traditions go back to the very first people who described these properties: for unknowable reasons they chose window in one case and self in the other, and everybody else copied these code examples.

Feel free to switch window and self wherever you encounter them, but be aware that you're flouting tradition if you do, and that less experienced coders might not understand your script.


Links with this target, such as <a href="somepage.html" target="ppk">, will open in this window.

In addition, you can use the name in the window.open() method we'll discuss in 6B:

window.open('somepage.html','ppk',[arguments]); 


Now the browser checks for a window named 'ppk'. If it finds one, then somepage.html is opened in this window. If it doesn't find one, it opens a new window that is assigned the name "ppk".

status and defaultStatus

The defaultStatus and status properties allow you to write texts in the window's status bar. This used to be the height of cool, but in these more enlightened days we've become aware that users may not be entirely happy with potentially intrusive or arbitrary status-bar messages.

Status-bar texts are automatically generated whenever the user mouses over a link; the status bar shows the URL of the page the link leads to.

The status property directly accesses the status-bar text and rewrites it. The defaultStatus property defines a text that should be shown if the status bar is not otherwise occupied (i.e., if the mouse is currently not over a link).

Setting the status bar text works as follows:

window.status = 'Take a look at this wonderful site!'; 


Now the status bar contains this text until the user mouses over another link.

The status property is commonly used to show a message when a user mouses over a link, but it's not quite as simple as the line above, because the default action of a mouseover on a link is to show the href in the status bar. If you use the status property in this way, you need to cancel the default action, or else your status text will immediately be overwritten by the link's href.

link.onmouseover = function () {    window.status = 'This is a GREAT link!';    return true; // or, in some browsers, false } 


You typically prevent a default action by returning false from the event-handling function. In the specific case of status-bar messages, though, Explorer and Mozilla require you to return true.



ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ISBN: N/A
EAN: N/A
Year: 2005
Pages: 116

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net