Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 175 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
175
Dung lượng
2,84 MB
Nội dung
496 Part III ✦ Document Objects Reference Passing data among pages via URLs It is not uncommon to want to preserve some pieces of data that exist in one page so that a script in another page can pick up where the script processing left off in the first page. You can achieve persistence across page loads through one of three techniques: the document.cookie (see Chapter 18), variables in framesetting documents, and the search string of a URL. That’s really what happens when you visit search and e-commerce sites that return information to your browser. Rather than store, say, your search criteria on the server, they spit the criteria back to the browser as part of the URL. The next time you activate that URL, the values are sent to the server for processing (for example, to send you the next page of search results for a particular query). Passing data among pages is not limited to client/server communication. You can use the search string strictly on the client-side to pass data from one page to another. Unless some CGI process on the server is programmed to do something with the search string, a Web server regurgitates the search string as part of the location data that comes back with a page. A script in the newly loaded page can inspect the search string (via the location.search property) and tear it apart to gather the data and put it into script variables. Take a look at Listings 17-6 through 17-8 to see a powerful application of this technique. As mentioned in the opening of Chapter 16 about frames, you can force a particular HTML page to open inside the frameset for which it is designed. But with the help of the search string, you can reuse the same framesetting document to accommodate any number of con- tent pages that go into one of the frames (rather than specifying a separate frameset for each possible combination of pages in the frameset). The listings in this section create a simple example of how to force a page to load in a frameset by passing some information about the page to the frameset. Thus, if a user has a URL to one of the content frames (perhaps it has been bookmarked by right-clicking the frame or it comes up as a search engine result), the page appears in its designated frameset the next time the user visits the page. The fundamental task going on in this scheme has two parts. The first is in each of the con- tent pages where a script checks whether the page is loaded inside a frameset. If the frameset is missing, a search string is composed and appended to the URL for the framesetting docu- ment. The framesetting document has its own short script that looks for the presence of the search string. If the string is there, the script extracts the search string data and uses it to load that specific page into the content frame of the frameset. Listing 17-6 is the framesetting document. The getSearchAsArray() function is more com- plete than necessary for this simple example, but you can use it in other instances to convert any number of name/value pairs passed in the search string (in traditional format of name1=value1&name2=value2&etc.) into an array whose indexes are the names (making it easier for scripts to extract a specific piece of passed data). Version branching takes place because, for convenience, the getSearchAsArray() function uses text and array methods that don’t exist in browsers prior to NN3 or IE4. Listing 17-6: A Smart Frameset <html> <head> <title>Example Frameset</title> <script type=”text/javascript”> // Convert location.search into an array of values // indexed by name. function getSearchAsArray() { var results = new Array(); windowObject.location.search 497 Chapter 17 ✦ Location and History Objects var input = unescape(location.search.substr(1)); if (input) { var srchArray = input.split(“&”); var tempArray = new Array(); for (var i = 0; i < srchArray.length; i++) { tempArray = srchArray[i].split(“=”); results[tempArray[0]] = tempArray[1]; } } return results; } function loadFrame() { if (location.search) { var srchArray = getSearchAsArray(); if (srchArray[“content”]) { self.content.location.href = srchArray[“content”]; } } } </script> </head> <frameset cols=”250,*” onload=”loadFrame()”> <frame name=”toc” src=”lst17-07.htm” /> <frame name=”content” src=”lst17-08.htm” /> </frameset> </html> Listing 17-7 is the HTML for the table of contents frame. Nothing elaborate goes on here, but you can see how normal navigation works for this simplified frameset. Listing 17-7: The Table of Contents <html> <head> <title>Table of Contents</title> </head> <body bgcolor=”#EEEEEE”> <h3>Table of Contents</h3> <hr /> <ul> <li><a href=”lst17-08.htm” target=”content”>Page 1</a></li> <li><a href=”lst17-08a.htm” target=”content”>Page 2</a></li> <li><a href=”lst17-08b.htm” target=”content”>Page 3</a></li> </ul> </body> </html> Listing 17-8 shows one of the content pages. As the page loads, the checkFrameset() func- tion is invoked. If the window does not load inside a frameset, the script navigates to the framesetting page, passing the current content URL as a search string. Notice that for browsers that support the location.replace() method, the loading of this page on its own does not get recorded to the browser’s history and isn’t accessed if the user hits the Back button. windowObject.location.search 498 Part III ✦ Document Objects Reference Listing 17-8: A Content Page <html> <head> <title>Page 1</title> <script type=”text/javascript”> function checkFrameset() { var isNav4 = (navigator.appName == “Netscape” && parseInt(navigator.appVersion) == 4); if (parent == window) { // Don’t do anything if running NN4 // so that the frame can be printed on its own if (isNav4 && window.innerWidth == 0) { return; } // Use replace() to keep current page out of history location.replace(“lst17-06.htm?content=” + escape(location.href)); } } // Invoke the function checkFrameset(); </script> </head> <body> <h1>Page 1</h1> <hr /> </body> </html> In practice, I recommend placing the code for the checkFrameset() function and call to it inside an external .js library and linking that library into each content document of the frameset. That’s why the function assigns the generic location.href property to the search string — you can use it on any content page. The code in Listings 17-6 through 17-8 establishes a frameset containing two frames. In the left frame is a Table of Contents that allows you to navigate among three different pages, the first of which is initially displayed in the right frame. The interesting thing about the example is how you can specify a new page in the content parameter of the search property, and then the page is opened within the frameset. For example, the following URL would result in the page hello.htm being opened in the right frame: lst17-06.htm?content=hello.htm In this example URL, the frameset page is first opened due to the inclusion of the file lst17-06.htm, while the hello.htm file is specified as the value of the content parameter. Related Item: location.href property. windowObject.location.search 499 Chapter 17 ✦ Location and History Objects Methods assign(“URL”) Returns: Nothing. Compatibility: WinIE3+, MacIE3+, NN2+, Moz1+, Safari1+ In earlier discussions about the location object, I said that you navigate to another page by assigning a new URL to the location object or location.href property. The location. assign() method does the same thing. In fact, when you set the location object to a URL, JavaScript silently applies the assign() method. No particular penalty or benefit comes from using the assign() method, except perhaps to make your code more understandable to others. Related Item: location.href property. reload(unconditionalGETBoolean) Returns: Nothing. Compatibility: WinIE4+, MacIE4+, NN3+, Moz1+, Safari1+ The location.reload() method may be named inappropriately because it makes you think of the Reload/Refresh button in the browser toolbar. The reload() method is actually more powerful than the Reload/Refresh button (a soft reload) in that it clears form control values that might otherwise survive the Reload/Refresh button. Note that MacIE and Safari do not preserve form control settings even with a soft reload. Most form elements retain their screen states when you click Reload/Refresh. Text and textarea objects maintain whatever text is inside them; radio buttons and checkboxes main- tain their checked status; select objects remember which item is selected. About the only items the Reload/Refresh button destroys are global variable values and any settable, but not visible, property (for example, the value of a hidden input object). I call this kind of reload a soft reload. Browsers are frustratingly irregular about the ways they reload a document in the memory cache. In theory, an application of the location.reload() method should retrieve the page from the cache if the page is still available there (while the history.go(0) method should be even gentler, preserving form element settings). Adding a true parameter to the method is supposed to force an unconditional GET to the server, ignoring the cached version of the page. Yet when it is crucial for your application to get a page from the cache (for speed) or from the server (to guarantee a fresh copy), the browser behaves in just the opposite way you want it to behave. Meta tags supposedly designed to prevent caching of a page rarely, if ever, work. Some scripters have had success in reloading the page from the server by setting location.href to the URL of the page, plus a slightly different search string (for example, based on a string representation of the Date object) so that there is no match for the URL in the cache. The bottom line is to be prepared to try different schemes to achieve the effect you want. And also be prepared to not get the results you need. windowObject.location.reload() 500 Part III ✦ Document Objects Reference Listing 17-9 provides a means of testing out the different outcomes of a soft reload versus a hard reload. Open this example page in a browser and click a radio button. Then enter some new text and make a choice in the select object. Clicking the Soft Reload/Refresh button invokes a method that reloads the document as if you had clicked the browser’s Reload/ Refresh button. It also preserves the visible properties of form elements. The Hard Reload button invokes the location.reload() method, which resets all objects to their default settings. Listing 17-9: Hard versus Soft Reloading <html> <head> <title>Reload Comparisons</title> <script type=”text/javascript”> function hardReload() { location.reload(true); } function softReload() { history.go(0); } </script> </head> <body> <form name=”myForm”> <input type=”radio” name=”rad1” value=”1” />Radio 1<br /> <input type=”radio” name=”rad1” value=”2” />Radio 2<br /> <input type=”radio” name=”rad1” value=”3” />Radio 3 <p><input type=”text” name=”entry” value=”Original” /></p> <p><select name=”theList”> <option>Red</option> <option>Green</option> <option>Blue</option> </select></p> <hr /> <input type=”button” value=”Soft Reload” onclick=”softReload()” /> <input type=”button” value=”Hard Reload” onclick=”hardReload()” /> </form> </body> </html> Related Item: history.go() method. replace(“URL”) Returns: Nothing. Compatibility: WinIE4+, MacIE4+, NN3+, Moz1+, Safari1+ In a complex Web site, you may have pages that you do not want to appear in the user’s his- tory list. For example, a registration sequence may lead the user to one or more intermediate HTML documents that won’t make much sense to the user later. You especially don’t want users to see these pages again if they use the Back button to return to a previous URL. The location.replace() method navigates to another page, but it does not let the current page stay in the queue of pages accessible via the Back button. windowObject.location.reload() 501 Chapter 17 ✦ Location and History Objects Although you cannot prevent a document from appearing in the history list while the user views that page, you can instruct the browser to load another document into the window and replace the current history entry with the entry for the new document. This trick does not empty the history list but instead removes the current item from the list before the next URL is loaded. Removing the item from the history list prevents users from seeing the page again by clicking the Back button later. Listing 17-10 shows how to use the replace() method to direct a Web browser to a new URL. Calling the location.replace() method navigates to another URL similarly to assigning a URL to the location. The difference is that the document doing the calling doesn’t appear in the history list after the new document loads. Check the history listing (in your browser’s usual spot for this information) before and after clicking Replace Me in Listing 17-10. Listing 17-10: Invoking the location.replace() Method <html> <head> <title>location.replace() Method</title> <script type=”text/javascript”> function doReplace() { location.replace(“lst17-01.htm”); } </script> </head> <body> <form name=”myForm”> <input type=”button” value=”Replace Me” onclick=”doReplace()” /> </form> </body> </html> Related Item: history object. history Object Property Method Event Handler current back() (None) length forward() next go() previous windowObject.history 502 Part III ✦ Document Objects Reference Syntax Accessing history object properties or methods: [window.]history.property | method([parameters]) About this object As a user surfs the Web, the browser maintains a list of URLs for the most recent stops. This list is represented in the scriptable object model by the history object. A script cannot sur- reptitiously extract actual URLs maintained in that list unless you use signed scripts (in NN4+ — see Chapter 46 on the CD-ROM) and the user grants permission. Under unsigned con- ditions, a script can methodically navigate to each URL in the history (by relative number or by stepping back one URL at a time), in which case the user sees the browser navigating on its own as if possessed by a spirit. Good Netiquette dictates that you do not navigate a user outside of your Web site without the user’s explicit permission. One application for the history object and its back() or go() methods is to provide the equivalent of a Back button in your HTML documents. That button triggers a script that checks for any items in the history list and then goes back one page. Your document doesn’t have to know anything about the URL from which the user lands at your page. As of NN4, the behavior of the Back and Forward buttons is also available through a pair of window methods: window.back() and window.forward(). The history object methods are not specific to a frame that is part of the reference. When the parent.frameName.history. back() method reaches the end of history for that frame, further invocations of that method are ignored. IE’s history mechanism is not localized to a particular frame of a frameset. Instead, the history.back() and history.forward() methods mimic the physical act of clicking the toolbar buttons. If you want to ensure cross-browser, if not cross-generational, behavior in a frameset, address references to the history.back() and history.forward() methods to the parent window. You should use the history object and its methods with extreme care. Your design must be smart enough to “watch” what the user is doing with your pages (for example, by checking the current URL before navigating with these methods). Otherwise, you run the risk of con- fusing your user by navigating to unexpected places. Your script can also get into trouble because it cannot detect where the current document is in the Back–Forward sequence in history. Properties current next previous Value: String. Read-Only Compatibility: WinIE-, MacIE-, NN4+, Moz1+, Safari- windowObject.history 503 Chapter 17 ✦ Location and History Objects To know where to go when you click the Back and Forward buttons, the browser maintains a list of URLs visited. To someone trying to invade your privacy and see what sites and pages you frequent, this information is valuable. That’s why the three properties that expose the actual URLs in the history list are restricted to pages with signed scripts and whose visitors have given permission to read sensitive browser data (see Chapter 46 on the CD-ROM). With signed scripts and permission, you can look through the entire array of history entries in any frame or window. Because the list is an array, you can extract individual items by index value. For example, if the array has 10 entries, you can see the fifth item by using normal array indexing methods: var fifthEntry = window.history[4]; No property or method exists that directly reveals the index value of the currently loaded URL, but you can script an educated guess by comparing the values of the current, next, and previous properties of the history object against the entire list. I personally don’t like some unknown entity watching over my shoulder while I’m on the Net, so I respect that same feeling in others and therefore discourage the use of these powers unless the user is given adequate warning. The signed script permission dialog box does not offer enough detail about the consequences of revealing this level of information. These properties were available in some form in NN3. Access to them required a short-lived security scheme called data tainting. That mechanism was never implemented fully and was replaced by signed scripts. Related Item: history.length property. length Value: Number. Read-Only Compatibility: WinIE3+, MacIE3+, NN2+, Moz1+, Safari1+ Use the history.length property to count the items in the history list. Unfortunately, this nugget of information is not particularly helpful in scripting navigation relative to the current location because your script cannot extract anything from the place in the history queue where the current document is located. If the current document is at the top of the list (the most recently loaded), you can calculate relative to that location. But users can use the Go/View menu to jump around the history list as they like. The position of a listing in the his- tory list does not change by virtue of navigating back to that document. A history.length of 1, however, indicates that the current document is the first one the user loaded since start- ing the browser software. Safari 1.0 uniformly reports history.length as zero. Listing 17-11 shows how to use the length property to notify users of how many pages they’ve visited. Note Note windowObject.history.length 504 Part III ✦ Document Objects Reference Listing 17-11: A Browser History Count <html> <head> <title>History Object</title> <script type=”text/javascript”> function showCount() { var histCount = window.history.length; if (histCount > 5) { alert(“My, my, you\’ve been busy. You have visited “ + histCount + “ pages so far.”); } else { alert(“You have been to “ + histCount + “ Web pages this session.”); } } </script> </head> <body> <form> <input type=”button” name=”activity” value=”My Activity” onclick=”showCount()” /> </form> </body> </html> Related Items: None. Methods back() forward() Returns: Nothing. Compatibility: WinIE3+, MacIE3+, NN2+, Moz1+, Safari1+ Prior to Navigator 4, the back() method acted identically to clicking the Back button in Navigator browsers. In Navigator 4, however, the history.back() method became window/frame-specific. Therefore, if you direct successive back() methods to a frame within a frameset, the method is ignored once it reaches the first document to be loaded into that frame. The Back button (and the window.back() method) unload the frameset and continue taking you back through the browser’s global history. If you deliberately lead a user to a dead end in your Web site, you should make sure that the HTML document provides a way to navigate back to a recognizable spot. Because you can easily create a new window that has no toolbar or menu bar (non-Macintosh browsers), you may end up stranding your users because they have no way of navigating out of a cul-de-sac in such a window. A button in your document should give the user a way back to the last location. windowObject.history.length() [...]... iframe element’s document object into an HTML editable document Visit http://www mozilla.org/editor for current details and examples doctype Value: DocumentType object reference Compatibility: WinIE-, MacIE5+, NN6+, Moz1+, Safari- Read-Only The doctype property comes from the W3C Core DOM and returns a DocumentType object — a representation of the DTD information for the document The DocumentType object... communications”,expdate,”/”,null,true); SetCookie (“goner”, “This cookie must die!”); document.write (document.cookie + “”); DeleteCookie (“goner”); document.write (document.cookie + “”); document.write (“ccpath = “ + GetCookie(“ccpath”) + “”); document.write (“ccname = “ + GetCookie(“ccname”) + “”); document.write (“tempvar = “ + GetCookie(“tempvar”) + “”); ... scriptable browsers to get the number of form objects in a document: document.forms.length In IE4+, you can also use document.tags[“FORM”].length And in the W3C DOM as implemented in IE5+ and NN6+/Moz1+/Safari1+, you can use document.getElementsByTagName(“FORM”).length The more modern versions provide generic ways of accessing elements (the tags array in IE4+ and the getElementsByTagName() method in the W3C... document.write(“There are “ + document.anchors.length + “ anchors defined for this document”) Related Items: anchor, location objects; document.links property applets[] Value: Array of applet objects Compatibility: WinIE3+, MacIE3+, NN2+, Moz1+, Safari1+ Read-Only The applets property refers to Java applets defined in a document by the... Example The document.applets property is defined automatically as the browser builds the object model for a document that contains applet objects You will rarely access this property, except to determine how many applet objects a document has Related Items: applet object bgColor (See alinkColor) body Value: body element object Compatibility: WinIE4+, MacIE4+, NN6+, Moz1+, Safari1+ Read/Write The document.body... NN6+, or some other W3C browser: document.body == document.getElementsByTagName(“body”)[0] Next, check out the body object’s property listings later in this chapter and enter the listings into the top text box to review their results For example: document.body.bgColor document.body.tagName Related Items: body element object charset Value: String Compatibility: WinIE4+, MacIE4+, NN-, Moz-, Safari- Read/Write... the document object’s place within the original object hierarchy Figure 18-1 clearly shows that the document object is a pivotal point for a large percentage of objects In the W3C DOM, the document object plays an even more important role as the container of all element objects delivered with the page: The document object is the root of the entire document tree window frame self top parent history document... nodeType† ownerDocument† parentNode† parentWindow plugins[] previousSibling† protocol readyState† referrer scripts[] security selection styleSheets[] tags[] title uniqueID† URL URLUnencoded vlinkColor width †See Chapter 15 511 512 Part III ✦ Document Objects Reference document Syntax Accessing document object properties or methods: [window.]document.property | method([parameters]) About this object A document... The document is a combination of the content and interface elements that make the Web page worth visiting In more recent browsers, which treat HTML elements as nodes of a hierarchical tree, the document object is the root node — that from which all other nodes grow Because the document object isn’t explicitly represented in an HTML document by tags or any other notation, the original designers of JavaScript. .. details objects contained by the document object Accessing arrays of objects contained by the document object Writing new document content to a window or frame Using the body element for IE window measurements ✦ ✦ ✦ ✦ 510 Part III ✦ Document Objects Reference document I must stress at the outset that many newcomers to JavaScript have the expectation that they can, on the fly, modify sections of a loaded page’s . Chapter 15. document 512 Part III ✦ Document Objects Reference Syntax Accessing document object properties or methods: [window.]document.property | method([parameters]) About this object A document. objects in a document: document.forms.length In IE4+, you can also use document.tags[“FORM”].length And in the W3C DOM as implemented in IE5+ and NN6+/Moz1+/Safari1+, you can use document.getElementsByTagName(“FORM”).length The. Setting Document Colors on the Fly (Browser Versions) Navigator Internet Explorer Color Property Windows Mac UNIX Windows Mac UNIX bgColor All 4+ 4+ All All 4+ All others 6+ 6+ 6+ All All 4+ Values