Section 14.2. Browser Location and History


14.2. Browser Location and History

This section discusses a window's Location and History objects. These objects provide access to the URL of the currently displayed document and enable you to load new documents or make the browser go back (or forward) to a previously viewed document.

14.2.1. Parsing URLs

The location property of a window (or frame) is a reference to a Location object; it represents the URL of the document currently being displayed in that window. The HRef property of the Location object is a string that contains the complete text of the URL. The toString( ) method of the Location object returns the value of the href property, so you can use location in place of location.href.

Other properties of this objectsuch as protocol, host, pathname, and searchspecify the various individual parts of the URL (see the Location object in Part IV for full details).

The search property of the Location object is an interesting one. It contains the portion, if any, of a URL following (and including) a question mark, which is often some sort of query string. In general, the question-mark syntax in a URL is a technique for embedding arguments in the URL. While these arguments are usually intended for scripts run on a server, there is no reason why they cannot also be used in JavaScript-enabled pages. Example 14-1 shows the definition of a general-purpose getArgs( ) function you can use to extract arguments from the search property of a URL.

Example 14-1. Extracting arguments from a URL

 /*  * This function parses ampersand-separated name=value argument pairs from  * the query string of the URL. It stores the name=value pairs in  * properties of an object and returns that object. Use it like this:  *  * var args = getArgs( );  // Parse args from URL  * var q = args.q || "";  // Use argument, if defined, or a default value  * var n = args.n ? parseInt(args.n) : 10;  */ function getArgs( ) {     var args = new Object( );     var query = location.search.substring(1);     // Get query string     var pairs = query.split("&");                 // Break at ampersand     for(var i = 0; i < pairs.length; i++) {         var pos = pairs[i].indexOf('=');          // Look for "name=value"         if (pos == -1) continue;                  // If not found, skip         var argname = pairs[i].substring(0,pos);  // Extract the name         var value = pairs[i].substring(pos+1);    // Extract the value         value = decodeURIComponent(value);        // Decode it, if needed         args[argname] = value;                    // Store as a property     }     return args;                                  // Return the object } 

14.2.2. Loading New Documents

Although the location property of a window refers to a Location object, you can assign a string value to the property. When you do this, the browser interprets the string as a URL and attempts to load and display the document at that URL. For example, you might assign a URL to the location property like this:

 // If the browser does not support the Document.getElementById function, // redirect to a static page that does not require that function. if (!document.getElementById) location = "staticpage.html"; 

Notice that the URL assigned to the location property in this example is a relative one. Relative URLs are interpreted relative to the page in which they appear, just as they would be if they were used in a hyperlink.

Example 14-7, at the end of this chapter, also uses the location property to load a new document.

It is surprising that there is not a method of the Window object that makes the browser load and display a new page. Historically, assigning a URL to the location property of a window has been the supported technique for loading new pages. The Location object does have two methods with related purposes, however. The reload( ) method reloads the currently displayed page from the web server; the replace( ) method loads and displays a URL that you specify. However, invoking the latter method for a given URL is different from assigning that URL to the location property of a window. When you call replace( ), the specified URL replaces the current one in the browser's history list rather than creating a new entry in that history list. Therefore, if you use replace( ) to overwrite one document with a new one, the Back button does not take the user back to the original document, as it does if you load the new document by assigning a URL to the location property. For web sites that use frames and display a lot of temporary pages (perhaps generated by a server-side script), replace( ) is often useful. Since temporary pages are not stored in the history list, the Back button is more useful to the user.

Finally, don't confuse the location property of the Window object, which refers to a Location object, with the location property of the Document object, which is simply a read-only string with none of the special features of the Location object. document.location is a synonym for document.URL, which is the preferred name for this property (because it avoids potential confusion). In most cases, document.location is the same as location.href. When there is a server redirect, however, document.location contains the URL as loaded, and location.href contains the URL as originally requested.

14.2.3. The History Object

The history property of the Window object refers to the History object for the window. The History object was originally designed to model the browsing history of a window as an array of recently visited URLs. This turned out to be a poor design choice, however. For important security and privacy reasons, it is almost never appropriate to give a script access to the list of web sites that the user has previously visited. Thus, the array elements of the History object are never actually accessible to scripts.

Although its array elements are inaccessible, the History object supports three methods. The back( ) and forward( ) methods move backward or forward in a window's (or frame's) browsing history, replacing the currently displayed document with a previously viewed one. This is similar to what happens when the user clicks on the Back and Forward browser buttons. The third method, go( ), takes an integer argument and can skip any number of pages forward (for positive arguments) or backward (for negative arguments) in the history list. Example 14-7, at the end of this chapter, demonstrates the back( ) and forward( ) methods of the History object.

Netscape and Mozilla-based browsers also support back( ) and forward( ) methods on the Window object itself. These nonportable methods perform the same action as the browser's Back and Forward buttons. When frames are used, window.back( ) may perform a different action than history.back( ).




JavaScript. The Definitive Guide
JavaScript: The Definitive Guide
ISBN: 0596101996
EAN: 2147483647
Year: 2004
Pages: 767

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