1. Trang chủ
  2. » Công Nghệ Thông Tin

JavaScript Bible 5th Edition 2004 phần 4 doc

175 202 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

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

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

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 mos

Trang 2

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 ascript in another page can pick up where the script processing left off in the first page Youcan achieve persistence across page loads through one of three techniques: the

document.cookie(see Chapter 18), variables in framesetting documents, and the searchstring of a URL That’s really what happens when you visit search and e-commerce sites thatreturn 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 thatURL, 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 thesearch string strictly on the client-side to pass data from one page to another Unless someCGI process on the server is programmed to do something with the search string, a Webserver 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.searchproperty) and tear it apart to gather the data and put it into script variables Take a look atListings 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 HTMLpage to open inside the frameset for which it is designed But with the help of the searchstring, 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 eachpossible combination of pages in the frameset) The listings in this section create a simpleexample of how to force a page to load in a frameset by passing some information about thepage to the frameset Thus, if a user has a URL to one of the content frames (perhaps it hasbeen bookmarked by right-clicking the frame or it comes up as a search engine result), thepage 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 tent pages where a script checks whether the page is loaded inside a frameset If the frameset

con-is mcon-issing, a search string con-is composed and appended to the URL for the framesetting ment The framesetting document has its own short script that looks for the presence of thesearch string If the string is there, the script extracts the search string data and uses it toload that specific page into the content frame of the frameset

docu-Listing 17-6 is the framesetting document The getSearchAsArray() function is more plete than necessary for this simple example, but you can use it in other instances to convertany number of name/value pairs passed in the search string (in traditional format of

com-name1=value1&name2=value2&etc.) into an array whose indexes are the names (making iteasier for scripts to extract a specific piece of passed data) Version branching takes placebecause, for convenience, the getSearchAsArray() function uses text and array methodsthat don’t exist in browsers prior to NN3 or IE4

Listing 17-6: A Smart Frameset

windowObject.location.search

Trang 3

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++) {

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

<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

Trang 4

Listing 17-8: A Content Page

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 historylocation.replace(“lst17-06.htm?content=” + escape(location.href));}

}// Invoke the functioncheckFrameset();

The code in Listings 17-6 through 17-8 establishes a frameset containing two frames In theleft frame is a Table of Contents that allows you to navigate among three different pages, thefirst 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 thenthe page is opened within the frameset For example, the following URL would result in thepage hello.htm being opened in the right frame:

Trang 5

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

textareaobjects 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.hrefto 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()

Trang 6

Listing 17-9 provides a means of testing out the different outcomes of a soft reload versus ahard reload Open this example page in a browser and click a radio button Then enter somenew text and make a choice in the select object Clicking the Soft Reload/Refresh buttoninvokes 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 Reloadbutton invokes the location.reload() method, which resets all objects to their default settings.

Listing 17-9: Hard versus Soft Reloading

}function softReload() {history.go(0);

<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>

<input type=”button” value=”Soft Reload” onclick=”softReload()” />

<input type=”button” value=”Hard Reload” onclick=”hardReload()” />

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 tory list For example, a registration sequence may lead the user to one or more intermediateHTML documents that won’t make much sense to the user later You especially don’t wantusers to see these pages again if they use the Back button to return to a previous URL Thelocation.replace()method navigates to another page, but it does not let the current pagestay in the queue of pages accessible via the Back button

his-windowObject.location.reload()

Trang 7

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

previous

windowObject.history

Trang 8

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 Thislist 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 (inNN4+ — 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 onits own as if possessed by a spirit Good Netiquette dictates that you do not navigate a useroutside 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 theequivalent of a Back button in your HTML documents That button triggers a script thatchecks for any items in the history list and then goes back one page Your document doesn’thave 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 ofwindow methods: window.back() and window.forward() The history object methods arenot 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 methodare ignored

IE’s history mechanism is not localized to a particular frame of a frameset Instead, thehistory.back()and history.forward() methods mimic the physical act of clicking thetoolbar buttons If you want to ensure cross-browser, if not cross-generational, behavior in aframeset, address references to the history.back() and history.forward() methods tothe parent window

You should use the history object and its methods with extreme care Your design must besmart enough to “watch” what the user is doing with your pages (for example, by checkingthe 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 troublebecause it cannot detect where the current document is in the Back–Forward sequence inhistory

Properties

current

next

previous

Compatibility: WinIE-, MacIE-, NN4+, Moz1+,

Safari-windowObject.history

Trang 9

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

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 hishis-tory.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

Trang 10

Listing 17-11: A Browser History Count

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.”);

}}

Compatibility: WinIE3+, MacIE3+, NN2+, Moz1+, Safari1+

Prior to Navigator 4, the back() method acted identically to clicking the Back button inNavigator browsers In Navigator 4, however, the history.back() method becamewindow/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 thatframe The Back button (and the window.back() method) unload the frameset and continuetaking 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 theHTML document provides a way to navigate back to a recognizable spot Because you caneasily create a new window that has no toolbar or menu bar (non-Macintosh browsers), youmay 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 lastlocation

windowObject.history.length()

Trang 11

Unless you need to perform some additional processing prior to navigating to the previous

location, you can simply place this method as the parameter to the event handler attribute of

a button definition To guarantee compatibility across all browsers, direct this method at the

parent document when used from within a frameset

Less likely to be scripted than the history.back() action is the method that performs

the opposite action: navigating forward one step in the browser’s history list The only time

you can confidently use the history.forward() method is to balance the use of the

history.back()method in the same script — where your script closely keeps track of how

many steps the script heads in either direction Use the history.forward() method with

extreme caution, and only after performing extensive user testing on your Web pages to make

sure that you’ve covered all user possibilities The same cautions about differences

intro-duced in NN4 for history.back() apply equally to history.forward(): Forward progress

extends only through the history listing for a given window or frame, not the entire browser

history list

Listings 17-12 and 17-13 provide a little workshop in which you can test the behavior of a

vari-ety of backward and forward navigation in different browsers Some features work only in NN4+

Listing 17-12: Navigation Lab Frameset

<b>Load a series of documents into the right frame by clicking some of

these links (make a note of the sequence you click on):</b>

<p><a href=”lst17-01.htm” target=”display”>Listing 17-1</a><br />

<a href=”lst17-05.htm” target=”display”>Listing 17-5</a><br />

<a href=”lst17-09.htm” target=”display”>Listing 17-9</a><br /></p>

Trang 12

Listing 17-13 (continued)

<li><b>NN4+</b> Substitute for toolbar buttons

<tt>window.back()</tt> and <tt>window.forward()</tt>:<inputtype=”button” value=”Back” onclick=”window.back()” /><inputtype=”button” value=”Forward” onclick=”window.forward()” /></li>

<li><tt>history.back()</tt> and <tt>history.forward()</tt> forrighthand frame:<input type=”button” value=”Back”

onclick=”parent.display.history.back()” /><input type=”button”value=”Forward” onclick=”parent.display.history.forward()” />

</li>

<li><tt>history.back()</tt> for this frame:<input type=”button”value=”Back” onclick=”history.back()” /></li>

<li><tt>history.back()</tt> for parent:<input type=”button”

value=”Back” onclick=”parent.history.back()” /></li>

Compatibility: WinIE3+, MacIE3+, NN2+, Moz1+, Safari1+

Use the history.go() method to script navigation within the history list currently stored inthe browser If you elect to use a URL as a parameter, however, that precise URL must alreadyexist in the history listing Therefore, do not regard this method as an alternate to setting thewindow.locationobject to a brand-new URL

For navigating n steps in either direction along the history list, use the relativeNumber

parameter of the history.go() method This number is an integer value that indicateswhich item in the list to use, relative to the current location For example, if the current URL

is at the top of the list (that is, the Forward button in the toolbar is dimmed), you need to usethe following method to jump to the URL two items backward in the list:

history.go(-2);

In other words, the current URL is the equivalent of history.go(0) (a method that reloadsthe window) A positive integer indicates a jump that many items forward in the history list.Thus, history.go(-1) is the same as history.back(), whereas history.go(1) is thesame as history.forward()

Alternatively, you can specify one of the URLs or document titles stored in the browser’s history list (titles appear in the Go/View menu) As security and privacy concerns increasedover time, this variant of the go() method has been reined in It’s best not to use the stringparameter in your scripting

Like most other history methods, your script finds it difficult to manage the history list or thecurrent URL’s spot in the queue That fact makes it even more difficult for your script to intel-ligently determine how far to navigate in either direction or to which specific URL or title

windowObject.history.back()

Trang 13

matches it should jump Use this method only for situations in which your Web pages are in

strict control of the user’s activity (or for designing scripts for yourself that automatically

crawl around sites according to a fixed regimen) Once you give the user control over

naviga-tion, you have no guarantee that the history list will be what you expect, and any scripts you

write that depend on a history object will likely break

In practice, this method mostly performs a soft reload of the current window using the 0

parameter

If you are developing a page for all scriptable browsers, be aware that Internet Explorer’s

go()method behaves a little differently than Netscape’s In IE4+, the matching string must

be part of the URL and not part of the document title, as in Navigator Additionally, the

reloading of a page with history.go(0) often returns to the server to reload the page

rather than reloading from the cache

Listing 17-14 contains sample code that demonstrates how to navigate through the history

list via the go() method Fill in either the number or text field of the page in Listing 17-14 and

then click the associated button The script passes the appropriate kind of data to the go()

method Be sure to use negative numbers for visiting a page earlier in the history

Listing 17-14: Navigating to an Item in History

Enter a number (+/-):<input type=”text” name=”histNum” size=”3”

value=”0” /> <input type=”button” value=”Go to Offset”

onclick=”doGoNum(this.form)” />

<p>Enter a word in a title:<input type=”text” name=”histWord” />

<input type=”button” value=”Go to Match”

Trang 15

The Document and

Body Objects

User interaction is a vital aspect of client-side JavaScript

script-ing, and most of the communication between script and user

takes place by way of the document object and its components

Understanding the scope of the document object within each of the

object models you support is key to implementing successful

cross-browser applications

Review the document object’s place within the original object

hierar-chy 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

ele-ment objects delivered with the page: The docuele-ment object is the

root of the entire document tree

Figure 18-1: The basic document object model hierarchy.

In fact, the document object and all that it contains is so big that I

have divided its discussion into many chapters, each focusing on

related object groups This chapter looks at the document object and

bodyobject (which have conceptual relationships), while each of the

succeeding chapters in this part of the book details objects

con-tained by the document object

windowparent

history document location

text radio button select

textarea checkbox reset option

link form anchor

Using the body elementfor IE window

measurements

Trang 16

I must stress at the outset that many newcomers to JavaScript have the expectation that theycan, on the fly, modify sections of a loaded page’s content with ease: replace some text here,change a table cell there However, understanding that these capabilities — an important part

of what is called Dynamic HTML — are available only in more recent browsers, specificallyIE4+/NN6+/Moz1+/Safari1+, is very important Not only do these browsers expose everyHTML element to script languages but they also automatically reflow the page when the size

of content changes under script control Pages on all previous browsers are limited to a smallset of modifiable objects, such as images and form elements

If your application requires compatibility with all scriptable browsers, you will be limited tochanging only a handful of other invisible properties after the page loads If these compatiblepages need to modify their contents based on user input or timed updates, consider design-ing your pages so that scripts write the contents; then let the scripts rewrite the entire pagewith your new settings

document Object

Compatibility: WinIE3+, MacIE3+, NN2+, Moz1+, Safari1+

activeElement attachEvent()† onactivate†

alinkColor captureEvents() onbeforecut†

anchors[] clearAttributes()† onbeforeeditfocus†

attributes† createAttribute() onclick†

body createDocumentFragment() oncontrolselect†

characterSet createEvent() ondblclick†

childNodes† createEventObject() ondrag†

cookie createStyleSheet() ondragenter†

defaultCharset createTextNode() ondragleave†

defaultView createTreeWalker() ondragover†

designMode detachEvent()† ondragstart†

documentElement execCommand() onhelp†

expando getElementsByName() onkeyup†

fgColor getElementsByTagName()† onmousedown†

fileCreatedDate getSelection() onmousemove†

document

Trang 17

Properties Methods Event Handlers

firstChild† mergeAttributes()† onmouseup†

frames[] queryCommandEnabled() onpropertychange†

height queryCommandIndterm() onreadyStatechange†

ids[] queryCommandState() onresizeend†

images[] queryCommandSupported() onresizestart†

implementation queryCommandText() onselectionchange

lastChild† queryCommandValue() onstop

Trang 18

Accessing document object properties or methods:

[window.]document.property | method([parameters])

About this object

A document object encompasses the totality of what exists inside the content region of abrowser window or window frame (excluding toolbars, status lines, and so on) The docu-ment is a combination of the content and interface elements that make the Web page worthvisiting 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 orany other notation, the original designers of JavaScript and object models decided to makethe document object the portal to many settings that were represented in HTML as belonging

to the body element That element’s tag contains attributes for document-wide attributes,such as background color (bgcolor) and link colors in various states (alink, link, andvlink) The body element also served as an HTML container for forms, links, and anchors.The document object, therefore, assumed a majority of the role of the body element But eventhen, the document object became the most convenient place to bind some properties thatextend beyond the body element, such as the title element and the URL of the link thatreferred the user to the page When viewed within the context of the HTML source code, theoriginal document object is somewhat schizophrenic Even so, the document object hasworked well as the basis for references to original object model objects, such as forms,images, and applets

This, of course, was before every HTML element, including the body element, was exposed as

an object via modern object models Amazingly, even with the IE4+ object model and W3CDOM — both of which treat the body element as an object separate from the documentobject — script compatibility with the original object model is quite easily accomplished Thedocumentobject has assumed a new schizophrenia, splitting its personality between the orig-inal object model and the one that places the document object at the root of the hierarchy,quite separate from the body element object it contains The object knows which “face” toput on based on the rest of the script syntax that follows it This means that quite often thereare multiple ways to achieve the same reference For example, you can use the followingstatement in all scriptable browsers to get the number of form objects in a document:document.forms.length

In IE4+, you can also usedocument.tags[“FORM”].lengthAnd in the W3C DOM as implemented in IE5+ and NN6+/Moz1+/Safari1+, you can usedocument.getElementsByTagName(“FORM”).length

The more modern versions provide generic ways of accessing elements (the tags array inIE4+ and the getElementsByTagName() method in the W3C DOM) to meet the requirements

of object models that expose every HTML (and XML) element as an object

document

Trang 19

Promoting the body element to the ranks of exposed objects presented its own challenges to

the new object model designers The body element is the true “owner” of some properties

that the original document object had to take on by default Most properties that had

belonged to the original document object were renamed in their transfer to the body element

For example, the original document.alinkColor property is the body.aLink property in the

new model But the bgColor property has not been renamed For the sake of code

compati-bility, the current versions of browsers recognize both properties, even though the W3C DOM

(in an effort to push the development world ahead) has removed the old versions as

proper-ties of what it conceives as the document object

As confusing as all of this may sound on the surface, understanding when to refer to the

origi-nal document object and when to use the new syntax doesn’t take long It all depends on

what you hang off the right edge of the reference Original properties and methods are

recog-nized as using the original document object; new properties and methods summon the

pow-ers of the new document object It’s all quite automatic Thankfully

Properties

activeElement

Compatibility: WinIE4+, MacIE4+, NN-, Moz-,

Safari-In IE4+, a script can examine the document.activeElement property to see which element

currently has focus The value returned is an element object reference You can use any of the

properties and methods listed in Chapter 15 to find out more about the object Be aware that

not all elements in all operating systems receive focus For example, buttons in IE4 for the

Macintosh do not receive focus

Although the element used to generate a mouse or keyboard event will most likely have focus

(except for MacIE4 buttons), don’t rely on the activeElement property to find out which

ele-ment generated an event The IE event.srcEleele-ment property is far more reliable

Example

Use The Evaluator (Chapter 13) with IE4+ to experiment with the activeElement property

Type the following statement into the top text box:

document.activeElement.value

After you press the Enter key, the Results box shows the value of the text box you just typed

into (the very same expression you just typed) But if you then click the Evaluate button, you

will see the value property of that button object appear in the Results box

Related Items: event.srcElement property.

document.activeElement

Trang 20

Value: Hexadecimal triplet or color name string. Mostly Read/Write

Compatibility: WinIE3+, MacIE3+, NN2+, Moz1+, Safari1+

These five properties are the script equivalent of the <body> tag attributes of the same name(although the property names are case-sensitive) All five settings can be read via scripting,but the ability to change some or all of these properties varies widely with browser and clientplatform Table 18-1 shows a summary of which browsers and platforms can set which of thecolor properties; Mozilla and Safari browsers support all of the color properties

Table 18-1: Setting Document Colors on the Fly (Browser Versions)

Values for all color properties can be either the common HTML hexadecimal triplet value (forexample, “#00FF00”) or any of the Netscape color names Internet Explorer recognizes theseplain language color names, as well But also be aware that some colors work only when theuser has the monitor set to 16- or 24-bit color settings

If you are scripting exclusively for IE4+ and NN6+, you should use the document.body object

to access these properties

Example

I select some color values at random to plug into three settings of the ugly colors group forListing 18-1 The smaller window displays a dummy button so that you can see how its dis-play contrasts with color settings Notice that the script sets the colors of the smaller win-dow by rewriting the entire window’s HTML code After changing colors, the script displaysthe color values in the original window’s textarea Even though some colors are set with thecolor constant values, properties come back in the hexadecimal triplet values You can exper-iment to your heart’s content by changing color values in the listing Every time you changethe values in the script, save the HTML file and reload it in the browser

Listing 18-1: Tweaking the Color of Page Elements

Trang 21

result += “bgColor: “ + newWindow.document.bgColor + “\n”;

result += “vlinkColor: “ + newWindow.document.vlinkColor + “\n”;

result += “linkColor: “ + newWindow.document.linkColor + “\n”;

thePage += “>Just so you can see the variety of items and color, <a “;

thePage += “href=’http://www.nowhere.com’>here\’s a link<\/a>, and <a

href=’http://home.netscape.com’> here is another link <\/a> you can

use on-line to visit and see how its color differs from the standard

Trang 22

Listing 18-1 (continued)

<input type=”button” name=”default” value=’Default Colors’

onclick=”drawPage(‘default’)” /> <input type=”button” name=”weird”value=”Ugly Colors” onclick=”drawPage(‘ugly’)” />

<p><textarea name=”results” rows=”3” cols=”20”>

</textarea></p>

<hr />

These buttons change the current document, but not correctly on allplatforms

<p><input type=”button” name=”default” value=’Default Colors’

onclick=”setColors(‘default’)” /> <input type=”button” name=”weird”value=”Ugly Colors” onclick=”setColors(‘ugly’)” /></p>

Related Items: body.aLink, body.bgColor, body.link, body.text, body.vLink properties.

anchors[]

Value: Array of anchor objects. Read-Only

Compatibility: WinIE3+, MacIE3+, NN2+, Moz1+, Safari1+

Anchor objects (described in Chapter 19) are points in an HTML document marked with

<a name=””>tags Anchor objects are referenced in URLs by a hash value between the page URL and anchor name Like other object properties that contain a list of nested objects, the document.anchorsproperty (notice the plural) delivers an indexed array of anchors in a docu-ment Use the array references to pinpoint a specific anchor for retrieving any anchor property.Anchor arrays begin their index counts with 0: The first anchor in a document, then, has thereference document.anchors[0] And, as is true with any built-in array object, you can findout how many entries the array has by checking the length property For example

var anchorCount = document.anchors.length;

The document.anchors property is read-only To script navigation to a particular anchor,assign a value to the window.location or window.location.hash object, as described inChapter 17’s location object discussion

Example

In Listing 18-2, I append an extra script to Listing 17-1 to demonstrate how to extract the ber of anchors in the document The document dynamically writes the number of anchorsfound in the document You will not likely ever need to reveal such information to users ofyour page, and the document.anchors property is not one that you will call frequently Theobject model defines it automatically as a document property while defining actual anchorobjects

num-document.alinkColor

Trang 23

Listing 18-2: Using Anchors to Navigate Through a Page

document.write(“<i>There are “ + document.anchors.length +

“ anchors defined for this document<\/i>”)

Value: Array of applet objects. Read-Only

Compatibility: WinIE3+, MacIE3+, NN2+, Moz1+, Safari1+

The applets property refers to Java applets defined in a document by the <applet> tag An

applet is not officially an object in the document until the applet loads completely

document.applets

Trang 24

Most of the work you do with Java applets from JavaScript takes place via the methods andvariables defined inside the applet Although you can reference an applet according to itsindexed array position within the applets array, you will more likely use the applet object’sname in the reference to avoid any confusion.

Example

The document.applets property is defined automatically as the browser builds the objectmodel 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. Read/Write

Compatibility: WinIE4+, MacIE4+, NN6+, Moz1+, Safari1+

The document.body property is a shortcut reference to the body element object in modernobject models As you can see in the discussion of the body element object later in this chap-ter, that object has many key properties that govern the look of the entire page Because thedocumentobject is the root of all references within any window or frame, the document.bodyproperty is easier to use to get to the body properties, rather than longer references normallyused to access HTML element objects in both the IE4+ and W3C object models

Example

Use The Evaluator (Chapter 13) to examine properties of the body element object First, toprove that the document.body is the same as the element object that comes back fromlonger references, enter the following statement into the top text box with either IE5+, 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 listingsinto the top text box to review their results For example:

document.body.bgColordocument.body.tagName

Related Items: body element object.

charset

Compatibility: WinIE4+, MacIE4+, NN-, Moz-,

Safari-The charset property reveals the character set used by the browser to render the currentdocument (the NN6+/Moz1+ version of this property is called characterSet) You can findpossible values for this property at

document.applets

Trang 25

Each browser and operating system has its own default character set Values may also be set

via a <meta> tag

Example

Use The Evaluator (Chapter 13) to experiment with the charset property To see the default

setting applied to the page, enter the following statement into the top text box:

document.charset

If you are running IE5+ for Windows and you enter the following statement, the browser will

apply a different character set to the page:

document.charset = “iso-8859-2”

If your version of Windows does not have that character set installed in the system, the

browser may ask permission to download and install the character set

Related Items: characterSet, defaultCharset properties.

characterSet

Compatibility: WinIE-, MacIE-, NN6+, Moz1+,

Safari-The characterSet property reveals the character set used by the browser to render the

cur-rent document (the IE4+ version of this property is called charset) You can find possible

values for this property at

http://www.iana.org/assignments/character-sets

Each browser and operating system has its own default character set Values may also be set

via a <meta> tag

Example

Use The Evaluator (Chapter 13) to experiment with the characterSet property in

NN6+/Moz1+ To see the default setting applied to the page, enter the following statement into

the top text box:

document.charset

Related Items: charset property.

compatMode

Compatibility: WinIE6+, MacIE6+, NN7+, Moz1+,

Safari-The compatMode property reveals the compatibility mode for the document, as determined

by the DOCTYPE element’s content The value for this property can be one of the following

string constants: BackCompat or CSS1Compat The default setting for the compatMode

prop-erty is BackCompat

document.compatMode

Trang 26

You may find it useful to check the compatibility mode of a document in order to carry outprocessing specific to one of the modes Following is an example of how you might branch tocarry out processing for backward-compatible documents:

if (document.compatMode == “BackCompat”) {// perform backward compatible processing}

Related Items: Standards Compatibility Modes (Chapter 13).

cookie

Compatibility: WinIE3+, MacIE3+, NN2+, Moz1+, Safari1+

The cookie mechanism in a Web browser lets you store small pieces of information on theclient computer in a reasonably secure manner In other words, when you need some tidbit ofinformation to persist at the client level while either loading diverse HTML documents ormoving from one session to another, the cookie mechanism saves the day The cookie is commonly used as a means to store the username and password you enter into a password-protected Web site The first time you enter this information into a CGI-governed form, theCGI program has Navigator write the information back to a cookie on your hard disk (usuallyafter encrypting the password) Rather than bothering you to enter the username and pass-word the next time you access the site, the server searches the cookie data stored for thatparticular server and extracts the username and password for automatic validation process-ing behind the scenes

Other applications of the cookie include storing user preferences and information about theuser’s previous visit to the site Preferences may include font styles or sizes and whether theuser prefers viewing content inside a frameset or not As shown in Chapter 54 on the CD-ROM,

a time stamp of the previous visit can allow a coded HTML page to display highlighted imagesnext to content that has changed since the user’s last visit, even if you have updated the page

several times in the interim Rather than hard-wiring “New” flags for your last visit, the scripts

highlight what’s new for the visitor

The cookie file

Allowing some foreign CGI program to read from and write to your hard disk may give youpause, but browser cookie mechanisms don’t just open up your drive’s directory for theworld to see (or corrupt) Instead, the cookie mechanism provides access to just one specialtext file (Navigator/Mozilla/Safari) or type of text file (Internet Explorer) located in a platform-specific spot on your drive

In Mozilla-based browsers, for example, the cookie file is named cookies.txt and is located in

a directory (whose name ends in slt) within the browser’s profile area In Windows, that

loca-tion is C:\\Windows\Applicaloca-tion Data\Mozilla\Profiles\[profilename]\; in Mac OSX, the location is [user]/Library/Mozilla/Profiles/[profilename]/ Internet Explorer for

Windows uses a different filing system: all cookies for each domain are saved in a specific file inside the C:\\Windows\Temporary Internet Files\ directory Filenamesbegin with Cookie: and include the username and domain of the server that wrote the cookie

domain-Safari cookies are recorded in an XML file named Cookies.plist within the [user]/Library/

Cookies/directory

document.compatMode

Trang 27

A cookie file is a text file If curiosity drives you to open a cookie file, I recommend you do so

only with a copy saved in another directory or folder Any alteration to the existing file can

mess up whatever valuable cookies are stored there for sites you regularly visit The data

for-mat for cookie files differs across browsers, in line with the different methodologies used for

filing cookies Inside the Netscape/Mozilla file (after a few comment lines warning you not to

manually alter the file) are lines of tab-delimited text Each return-delimited line contains one

cookie’s information The cookie file is just like a text listing of a database In each of the IE

cookie files, the same data points are stored for a cookie as for Navigator, but the items are in

a return-delimited list The structure of these files is of no importance to scripting cookies,

because all browsers utilize the same syntax for reading and writing cookies through the

document.cookieproperty

As you experiment with browser’s cookies, you will be tempted to look into the cookie file

after a script writes some data to the cookie The cookie file usually will not contain the

newly written data, because in most browsers cookies are transferred to disk only when the

user quits the browser; conversely, the cookie file is read into the browser’s memory when it

is launched While you read, write, and delete cookies during a browser session, all activity is

performed in memory (to speed up the process) to be saved later

A cookie record

Among the “fields” of each cookie record are the following (not necessarily in this order):

✦ Domain of the server that created the cookie

✦ Information on whether you need a secure HTTP connection to access the cookie

✦ Pathname of URL(s) capable of accessing the cookie

✦ Expiration date of the cookie

✦ Name of the cookie entry

✦ String data associated with the cookie entry

Notice that cookies are domain-specific In other words, if one domain creates a cookie,

another domain cannot access it through the browser’s cookie mechanism behind your back

That reason is why it’s generally safe to store what I call throwaway passwords (the

user-name/password pairs required to access some free registration-required sites) in cookies

Moreover, sites that store passwords in a cookie usually do so as encrypted strings, making it

more difficult for someone to hijack the cookie file from your unattended PC and figure out

what your personal password scheme may be

Cookies also have expiration dates Because some browsers may allow no more than a fixed

number of cookies (300 in NN), the cookie file can get pretty full over the years Therefore, if a

cookie needs to persist past the current browser session, it should have an expiration date

established by the cookie writer Browsers automatically clean out any expired cookies

Not all cookies have to last beyond the current session, however In fact, a scenario in which

you use cookies temporarily while working your way through a Web site is quite typical

Many shopping sites employ one or more temporary cookie records to behave as the

shop-ping cart for recording items you intend to purchase These items are copied to the order

form at checkout time But after you submit the order form to the server, that client-side data

has no particular value As it turns out, if your script does not specify an expiration date, the

browser keeps the cookie fresh in memory without writing it to the cookie file When you quit

the browser, that cookie data disappears as expected

Note

document.cookie

Trang 28

Saving cookies

To write cookie data to the cookie file, you use a simple JavaScript assignment operator withthe document.cookie property But the formatting of the data is crucial to achieving suc-cess Here is the syntax for assigning a value to a cookie (optional items are in brackets;placeholders for data you supply are in italics):

document.cookie = “userName=Fred”;

If the browser sees no existing cookie in the current domain with this name, it automaticallycreates the cookie entry for you; if the named cookie already exists, the browser replaces theold data with the new data Retrieving the document.cookie property at this point yields thefollowing string:

userName=FredYou can omit all the other cookie-setting properties, in which case the browser uses defaultvalues, as explained in a following section For temporary cookies (those that don’t have topersist beyond the current browser session), the name/value pair is usually all you need.The entire name/value pair must be a single string with no semicolons, commas, or characterspaces To take care of spaces between words, preprocess the value with the JavaScriptescape()function, which URL-encodes the spaces as %20 (and then be sure to unescape()the value to restore the human-readable spaces when you retrieve the cookie later)

You cannot save a JavaScript array or object to a cookie But with the help of the Array.join()method, you can convert an array to a string; use String.split() to re-create the array afterreading the cookie at a later time These two methods are available in NN3+/Moz1+, IE4+, andSafari1+

document.cookie

Trang 29

Expiration dates, when supplied, must be passed as Greenwich Mean Time (GMT) strings

(see Chapter 29 about time data) To calculate an expiration date based on today’s date, use

the JavaScript Date object as follows:

var exp = new Date();

var oneYearFromNow = exp.getTime() + (365 * 24 * 60 * 60 * 1000);

exp.setTime(oneYearFromNow);

Then convert the date to the accepted GMT string format:

document.cookie = “userName=Fred; expires=” + exp.toGMTString();

In the cookie file, the expiration date and time is stored as a numeric value (seconds) but, to

set it, you need to supply the time in GMT format You can delete a cookie before it expires by

setting the named cookie’s expiration date to a time and date earlier than the current time

and date The safest expiration parameter is

expires=Thu, 01-Jan-70 00:00:01 GMT

Omitting the expiration date signals the browser that this cookie is temporary The browser

never writes it to the cookie file and forgets it the next time you quit the browser

Path

For client-side cookies, the default path setting (the current directory) is usually the best

choice You can, of course, create a duplicate copy of a cookie with a separate path (and

domain) so that the same data is available to a document located in another area of your site

(or the Web)

Domain

To help synchronize cookie data with a particular document (or group of documents), the

browser matches the domain of the current document with the domain values of cookie

entries in the cookie file Therefore, if you were to display a list of all cookie data contained in

a document.cookie property, you would get back all the name/value cookie pairs from the

cookie file whose domain parameter matches that of the current document

Unless you expect the document to be replicated in another server within your domain, you

can usually omit the domain parameter when saving a cookie Default behavior automatically

supplies the domain of the current document to the cookie file entry Be aware that a domain

setting must have at least two periods, such as

.mcom.com

.hotwired.com

Or, you can write an entire URL to the domain, including the http:// protocol

SECURE

If you omit the SECURE parameter when saving a cookie, you imply that the cookie data is

accessible to any document or CGI program from your site that meets the other domain- and

path-matching properties For client-side scripting of cookies, you should omit this parameter

when saving a cookie

document.cookie

Trang 30

Retrieving cookie data

Cookie data retrieved via JavaScript is contained in one string, including the whole name-datapair Even though the cookie file stores other parameters for each cookie, you can retrieve onlythe name-data pairs via JavaScript Moreover, when two or more (up to a maximum of 20) cook-ies meet the current domain criteria, these cookies are also lumped into that string, delimited

by a semicolon and space For example, a document.cookie string may look like this:

var data = unescape(document.cookie.substring(7,document.cookie.length));The first parameter of the substring() method includes the equal sign to separate the namefrom the data

A better approach is to create a general-purpose function that can work with single- or entry cookies Here is one I use in some of my pages:

multiple-function getCookieData(labelName) {var labelLen = labelName.length;

// read cookie property only once for speedvar cookieData = document.cookie;

var cLen = cookieData.length;

var i = 0;

var cEnd;

while (i < cLen) {var j = i + labelLen;

if (cookieData.substring(i,j) == labelName) {cEnd = cookieData.indexOf(“;”,j);

if (cEnd == -1) {cEnd = cookieData.length;

}return unescape(cookieData.substring(j+1, cEnd));

}i++;

}return “”;

}Calls to this function pass the label name of the desired cookie as a parameter The functionparses the entire cookie string, chipping away any mismatched entries (through the semi-colons) until it finds the cookie name

If all of this cookie code still makes your head hurt, you can turn to a set of functions devised

by experienced JavaScripter and Web site designer Bill Dortch of hIdaho Design His cookiefunctions provide generic access to cookies that you can use in all of your cookie-relatedpages Listing 18-3 shows Bill’s cookie functions, which include a variety of safety nets fordate calculation bugs that appeared in some older versions of Netscape Navigator Don’t beput off by the length of the listing: Most of the lines are comments

document.cookie

Trang 31

Listing 18-3: Bill Dortch’s Cookie Functions

// Written by: Bill Dortch, hIdaho Design

// The following functions are released to the public domain

//

// This version takes a more aggressive approach to deleting

// cookies Previous versions set the expiration date to one

// millisecond prior to the current time; however, this method

// did not work in Netscape 2.02 (though it does in earlier and

// later versions), resulting in “zombie” cookies that would not

// die DeleteCookie now sets the expiration date to the earliest

// usable date (one second into 1970), and sets the cookie’s value

// to null for good measure

//

// Also, this version adds optional path and domain parameters to

// the DeleteCookie function If you specify a path and/or domain

// when creating (setting) a cookie**, you must specify the same

// path/domain when deleting it, or deletion will not occur

//

// The FixCookieDate function must now be called explicitly to

// correct for the 2.x Mac date bug This function should be

// called *once* after a Date object is created and before it

// is passed (as an expiration date) to SetCookie Because the

// Mac date bug affects all dates, not just those passed to

// SetCookie, you might want to make it a habit to call

// FixCookieDate any time you create a new Date object:

//

// var theDate = new Date();

// FixCookieDate (theDate);

//

// Calling FixCookieDate has no effect on platforms other than

// the Mac, so there is no need to determine the user’s platform

// prior to calling it

//

// This version also incorporates several minor coding improvements

//

// **Note that it is possible to set multiple cookies with the same

// name but different (nested) paths For example:

//

// SetCookie (“color”,”red”,null,”/outer”);

// SetCookie (“color”,”blue”,null,”/outer/inner”);

//

// However, GetCookie cannot distinguish between these and will return

// the first cookie that matches a given name It is therefore

// recommended that you *not* use the same name for cookies with

// different paths (Bear in mind that there is *always* a path

Continued

document.cookie

Trang 32

// “Second Helping” Version (21-Jan-96)// - Added path, domain and secure parameters to SetCookie// - Replaced home-rolled encode/decode functions with Netscape’s// new (then) escape and unescape functions

//

// http://www.netscape.com/newsref/std/cookie_spec.html //

//******************************************************************//

// “Internal” function to return the decoded value of a cookie//

function getCookieVal (offset) {var endstr = document.cookie.indexOf (“;”, offset);

if (endstr == -1) {endstr = document.cookie.length;

}return unescape(document.cookie.substring(offset, endstr));

}//

// Function to correct for 2.x Mac date bug Call this function to// fix a date object prior to passing it to SetCookie

// IMPORTANT: This function should only be called *once* for// any given date object! See example at the end of this document.//

function FixCookieDate (date) {var base = new Date(0);

var skew = base.getTime(); // dawn of (Unix) time - should be 0

if (skew > 0) { // Except on the Mac - ahead of its timedate.setTime (date.getTime() - skew);

}}//

// Function to return the value of the cookie specified by “name”.// name - String object containing the cookie name

// returns - String object containing the cookie value, or null if// the cookie does not exist

//

document.cookie

Trang 33

function GetCookie (name) {

var arg = name + “=”;

var alen = arg.length;

var clen = document.cookie.length;

// Function to create or update a cookie

// name - String object containing the cookie name

// value - String object containing the cookie value May contain

// any valid string characters

// [expires] - Date object containing the expiration data of the

// cookie If omitted or null, expires the cookie at the end of the

// current session

// [path] - String object indicating the path for which the cookie is

// valid

// If omitted or null, uses the path of the calling document

// [domain] - String object indicating the domain for which the cookie

// is valid If omitted or null, uses the domain of the calling

// document

// [secure] - Boolean (true/false) value indicating whether cookie

// transmission requires a secure channel (HTTPS)

//

// The first two parameters are required The others, if supplied, must

// be passed in the order listed above To omit an unused optional

// field, use null as a place holder For example, to call SetCookie

// using name, value and path, you would code:

// To set a secure cookie for path “/myPath”, that expires after the

// current session, you might code:

//

// SetCookie (myCookieVar, cookieValueVar, null, “/myPath”, null,

// true);

//

function SetCookie (name,value,expires,path,domain,secure) {

document.cookie = name + “=” + escape (value) +

((expires) ? “; expires=” + expires.toGMTString() : “”) +

((path) ? “; path=” + path : “”) +

((domain) ? “; domain=” + domain : “”) +

((secure) ? “; secure” : “”);

}

Continued

document.cookie

Trang 34

// no path was specified when creating the cookie.

// domain - String object containing the domain of the cookie to // delete This MUST be the same as the domain used to // create the cookie, or null/omitted if no domain was // specified when creating the cookie

//

function DeleteCookie (name,path,domain) {

if (GetCookie(name)) {document.cookie = name + “=” +((path) ? “; path=” + path : “”) +((domain) ? “; domain=” + domain : “”) +

“; expires=Thu, 01-Jan-70 00:00:01 GMT”;

}}//

// Examples//

var expdate = new Date ();

FixCookieDate (expdate); // Correct for Mac date bug (call only once)expdate.setTime (expdate.getTime() + (24 * 60 * 60 * 1000)); // 24 hrsSetCookie (“ccpath”, “http://www.hidaho.com/colorcenter/”, expdate);SetCookie (“ccname”, “hIdaho Design ColorCenter”, expdate);

SetCookie (“tempvar”, “This is a temporary cookie.”);

SetCookie (“ubiquitous”, “This cookie will work anywhere in this domain”,null,”/”);

SetCookie (“paranoid”, “This cookie requires secure communications”,expdate,”/”,null,true);

SetCookie (“goner”, “This cookie must die!”);

document.write (document.cookie + “<br>”);

DeleteCookie (“goner”);

document.write (document.cookie + “<br>”);

document.write (“ccpath = “ + GetCookie(“ccpath”) + “<br>”);

document.write (“ccname = “ + GetCookie(“ccname”) + “<br>”);

document.write (“tempvar = “ + GetCookie(“tempvar”) + “<br>”);

Because each named cookie stores plain text, you can create your own text-based data tures to accommodate multiple pieces of information per cookie (But also watch out for a

struc-document.cookie

Trang 35

practical limit of 2,000 characters per name/value pair within the 4,000 character maximum

for any domain’s combined cookies.) The trick is determining a delimiter character that won’t

be used by any of the data in the cookie In Decision Helper (in Chapter 55 on the CD-ROM),

for example, I use a period to separate multiple integers stored in a cookie

With the delimiter character established, you must then write functions that concatenate

these “subcookies” into single cookie strings and extract them on the other side It’s a bit

more work, but well worth the effort to have the power of persistent data on the client

Example

Experiment with the last group of statements in Listing 18-3 to create, retrieve, and delete

cookies You can also experiment with The Evaluator by assigning a name/value pair string

to document.cookie, and then examining the value of the cookie property

Related Items: String object methods (Chapter 27).

defaultCharset

Compatibility: WinIE4+, MacIE4+, NN-, Moz-,

Safari-The defaultCharset property reveals the character set used by the browser to render the

current document You can find possible values for this property at

http://www.iana.org/assignments/character-sets

Each browser and operating system has its own default character set Values may also be set

via a <meta> tag The difference between the defaultCharset and charset properties is not

clear, especially because both are read/write (although modifying the defaultCharset

prop-erty has no visual effect on the page) However, if your scripts temporarily modify the charset

property, you can use the defaultCharset property to return to the original character set:

document.charset = document.defaultCharset;

Example

Use The Evaluator (Chapter 13) to experiment with the defaultCharset property To see the

default setting applied to the page, enter the following statement into the top text box:

document.defaultCharset

Related Items: charset, characterSet properties.

defaultView

Value: window or frame object reference. Read-Only

Compatibility: WinIE-, MacIE-, NN6+, Moz1+,

Safari-The defaultView property returns a reference to the object serving as the “viewer” for the

document The viewer is responsible for rendering the document, and in NN6+ the object

returned in the defaultView property is the window or frame object that contains the

docu-ment This W3C DOM Level 2 property provides access to computed CSS values being applied

to any HTML element (via the document.defaultView.getComputedStyle() method, or

more simply, the window.getComputedStyle() method)

Related Items: window and frame properties; window.getComputedStyle() method.

document.defaultView

Trang 36

Compatibility: WinIE5+, MacIE-, NN7.1, Moz1.4+,

Safari-The designMode property is applicable only when WinIE5+ technology is being used as acomponent in another application The property controls whether the browser module isbeing used for HTML editing Modifying the property from within a typical HTML page in theIE5+ browser has no effect But on the Mozilla side, the property can be used to turn aniframeelement’s document object into an HTML editable document Visit http://www.mozilla.org/editorfor current details and examples

doctype

Value: DocumentType object reference. Read-Only

Compatibility: WinIE-, MacIE5+, NN6+, Moz1+,

Safari-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 (if one

is explicitly defined in the source code) is the first child node of the root document node (and

is thus a sibling to the HTML element)

Table 18-2 shows the typical DocumentType object property list and values for a genericHTML page Future DOM specifications will allow these properties to be read/write

Table 18-2: DocumentType Object in NN6+/Moz1+

entities nullinternalSubset (empty)

notations nullpublicId -//W3C//DTD XHTML 1.0 Transitional//ENsystemId http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd

Related Items: Node object (Chapter 14).

documentElement

Value: HTML or XML element object reference. Read-Only

Compatibility: WinIE5+, MacIE5+, NN6+, Moz1+, Safari1+

The documentElement property returns a reference to the HTML (or XML) element objectthat contains all of the content of the current document The naming of this property is a bitmisleading, because the root document node is not an element, but its only child node is theHTML (or XML) element for the page At best, you can think of this property as providingscripts with an “element face” to the document object and document node associated withthe page currently loaded in the browser

document.designMode

Trang 37

Use The Evaluator (Chapter 13) to examine the behavior of the documentElement property

In IE5+/W3C, enter the following statement into the top text field:

document.documentElement.tagName

The result is HTML, as expected

Related Items: ownerDocument property (Chapter 15).

domain

Compatibility: WinIE4+, MacIE4+, NN3+, Moz1+, Safari1+

Security restrictions can get in the way of sites that have more than one server at their

domain Because some objects, especially the location object, prevent access to properties

of other servers displayed in other frames, legitimate access to those properties are blocked

For example, it’s not uncommon for popular sites to have their usual public access site on a

server named something such as www.popular.com If a page on that server includes a front

end to a site search engine located at search.popular.com, visitors who use browsers with

these security restrictions are denied access

To guard against that eventuality, a script in documents from both servers can instruct the

browser to think both servers are the same In the preceding example, you would set the

document.domainproperty in both documents to popular.com Without specifically setting

the property, the default value includes the server name as well, thus causing a mismatch

between hostnames

Before you start thinking that you can spoof your way into other servers, be aware that you

can set the document.domain property only to servers with the same domain (following the

“two-dot” rule) as the document doing the setting Therefore, documents originating only

from xxx.popular.com can set their document.domain properties to popular.com server

Related Items: window.open() method; window.location object; security (Chapter 46 on

the CD-ROM)

embeds[]

Value: Array of embed element objects. Read-Only

Compatibility: WinIE4+, MacIE4+, NN3+, Moz1+, Safari1+

Although now supplanted by the <object> tag, the <embed> tag used to be the markup that

loaded data requiring a plug-in application to play or display The document.embeds

prop-erty is an array of embed element objects within the document:

var count = document.embeds.length;

For controlling those plug-ins in Navigator and Mozilla-based browsers, you can use the

LiveConnect technology, described in Chapter 44 on the CD-ROM

Related Items: embed element object (Chapter 40 on the CD-ROM).

document.embeds

Trang 38

Compatibility: WinIE4+, MacIE4+, NN-, Moz-,

Safari-Microsoft calls any custom property that is not a native property of the document object an

expando property By default, most objects in recent generations of browsers allow scripts to

add new properties of objects as a way to temporarily store data without explicitly definingglobal variables For example, if you want to maintain an independent counter of how often afunction is invoked, you can create a custom property of the document object and use it asthe storage facility:

document.counter = 0;

IE4+ lets you control whether the document object is capable of accepting expando properties.The default value of the document.expando property is true, thus allowing custom properties.But the potential downside to this permissiveness, especially during the page constructionphase, is that a misspelled native property name is gladly accepted by the document object.You may not be aware of why the title bar of the browser window doesn’t change when youassign a new string to the document.Title property (which, in the case-sensitive world ofJavaScript, is distinct from the native document.title property)

Example

Use The Evaluator (Chapter 13) to experiment with the document.expando property in IE4+.Begin by proving that the document object can normally accept custom properties Type thefollowing statement into the top text field:

document.spooky = “Boo!”

This property is now set and stays that way until the page is either reloaded or unloaded.Now freeze the document object’s properties with the following statement:

document.expando = false

If you try to add a new property, such as the following, you receive an error:

document.happy = “tra la”

Interestingly, even though document.expando is turned off, the first custom property is stillaccessible and modifiable

Related Items: prototype property of custom objects (Chapter 33).

Value: String, Integer (fileSize). Read-Only

Compatibility: WinIE4+, MacIE4+, NN-, Moz-, document.expando

Trang 39

Safari-These three IE-specific properties return information about the file that holds the current

document The first two properties (not implemented in MacIE) reveal the dates on which the

current document’s file was created and modified For an unmodified file, its creation and

modified dates are the same The fileSize property reveals the number of bytes of the file

Date values returned for the first two properties are formatted differently between IE4 and

IE5+ The former provides a full readout of the day and date; the latter in a format similar to

mm/dd/yyyy Note, however, that the values contain only the date and not the time In any

case, you can use the values as the parameter to a new Date() constructor function You can

then use date calculations for such information as the number of days between the current

day and the most recent modification

Not all servers may provide the proper date or size information about a file or in a format that

IE can interpret Test your implementation on the deployment server to ensure compatibility

Also, be aware that these properties can be read only for a file that is loaded in the browser

JavaScript by itself cannot get this information about files that are on the server but not

loaded in the browser

IE5.5+ exposes a property called fileUpdatedDate, but the property does not return any

data This property may be a phantom property left over from a prerelease version

Example

Listing 18-4 dynamically generates several pieces of content relating to the creation and

modi-fication dates of the file, as well as its size More importantly, the listing demonstrates how to

turn a value returned by the file date properties into a genuine date object that can be used

for date calculations In the case of Listing 18-4, the calculation is the number of full days

between the creation date and the day someone views the file Notice that the dynamically

generated content is added very simply via the innerText properties of carefully located

spanelements in the body content

Listing 18-4: Displaying File Information for a Web Page

var created = document.fileCreatedDate;

var modified = document.fileModifiedDate;

document.getElementById(“created”).innerText = created;

document.getElementById(“modified”).innerText = modified;

var createdDate = new Date(created).getTime();

var today = new Date().getTime();

var diff = Math.floor((today - createdDate) / (1000*60*60*24));

Trang 40

<p>It has been <span id=”diff”>&nbsp;</span> days since this file wascreated.</p>

</body>

</html>

Related Items: lastModified property.

forms[]

Compatibility: WinIE3+, MacIE3+, NN2+, Moz1+, Safari1+

As I show in Chapter 21, which is dedicated to the form object, an HTML form (anythingdefined inside a <form> </form> tag pair) is a JavaScript object unto itself You can create

a valid reference to a form according to its name (assigned via a form’s name attribute) Forexample, if a document contains the following form definition

of the HTML code) If your document defines one form, the forms property is an array oneentry in length; with three separate forms in the document, the array is three entries long.Use standard array notation to reference a particular form from the document.forms array.For example, the first form in a document (the “zeroth” entry of the document.forms array)

is referenced asdocument.forms[0]

Any of the form object’s properties or methods are available by appending the desired erty or method name to the reference For example, to retrieve the value of an input text fieldnamed homePhone from the second form of a document, the reference you use is

prop-document.forms[1].homePhone.valueOne advantage to using the document.forms property for addressing a form object or ele-ment instead of the actual form name is that you may be able to generate a library of general-izable scripts that know how to cycle through all available forms in a document and hunt for

a form that has some special element and property The following script fragment (part of a

repeat loop described more fully in Chapter 31) uses a loop-counting variable (i) to help the

script check all forms in a document:

document.fileCreatedDate

Ngày đăng: 12/08/2014, 19:21

TỪ KHÓA LIÊN QUAN