Image, Area, and Map Objects (Chapter 22)

Một phần của tài liệu tài liệu hướng dẫn sử dụng javascript (Trang 304 - 364)

W hile both the location and history objects contain valuable information about the user’s Web surfing habits and even the content of forms, they could also be abused by nefarious scripts that wish to invade the privacy of unsuspecting site visitors. As a result, browsers do not expose the private details to scripts (except in NN4+ via signed scripts and the user’s express permission).

The location object, however, is still an important object to know and exploit. As shown in the examples here, you can use it as one cookie-free way to pass text data from one page to another. And the object remains the primary way scripts load a new page into the browser.

Examples Highlights

♦ The frameset listing for the location.host property demonstrates several location object properties. You also find an example of how signed scripts can be used in NN4+ to access location object properties for pages served by a different domain.

♦ Listings for the 1 o c a t i o n . search property pass data from one page to another via a URL. In this case, a script in a page not only makes sure that your site gets served within the prescribed frameset, but the specific page also gets loaded into one of the frames, even if it is not the page specified in the frameset’s definition.

♦ Observe the location. replace() method’s example.

This method comes in handy when you don’t want one of your pages to become part of the browser’s history:

Clicking the Back button skips over the replaced page.

♦ Run Listings 17-12 and 17-13 for the hi s t o r y . b a c k ( ) method to see how the behavior of this method varies among browsers. Consult the JavaScript Bible text for details on the evolution of this method.

♦ ♦ ♦ ♦ In This C ha p te r Loading new pages and other media types via the 1 ocati on object Passing data between pages via URLs N avigating through the browser history under script control

♦ ♦ ♦ ♦

2 0 6 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

Location Object

Properties

hash

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

C om pa tib ility / / / / / / / /

Example

When you load the script in Listing 17-1, adjust the size of the browser window so only one section is visible at a time. When you click a button, its script navigates to the next logical section in the progression and eventually takes you back to the top.

Listing 17-1 : A Document w ith Anchors

<HTML>

<HEAD>

<TITLE>1ocation.hash Property</TITLE>

<SCRIPT LANGUAGE“ "JavaScript">

function goNextAnchor(where) { window.location.hash = where )

</SCRIPT>

</HEAD>

<B0DY>

<A NAME="start”X H l > T o p < / H l X / A >

<F0RM>

< INPUT TYPE="button" NAME-"next" VALUE="NEXT" onClick-"goNextAnchor('secl')">

</F0RM>

<HR>

<A NAME= "seel "XHl>Secti on 1 < / H X / A >

<F0RM>

< INPUT TYPE="button" NAME="next" VALUE="NEXT" onClick="goNextAnchor( ’sec2’ )">

</F0RM>

<HR>

<A NAME="sec2"XHl>Secti on 2 </h lX/A>

<F0RM>

<INPUT TYPE=”button" NAME="next" VALUE=”NEXT" onClick="goNextAnchor(’sec3')">

</F0RM>

<HR>

<A NAME="sec3"XHl>Secti on 3 < / H X / A >

<F0RM>

w/nrfowO/j/ecf.location.hash

Chapter 3 ♦ Location and History Objects (Chapter 17) 2 0 7

<INPUT TYPE="button" NAME="next" VALUE=”BACK TO TOP”

onClick="goNextAnchor('start')">

</F0RM>

</B0DY>

</HTML>

Anchor names are passed as parameters with each button’s on Cl i ck event han­

dler. Instead of going through the work of assembling a wi n d o w . 1 ocati on value in the function by appending a literal hash mark and the value for the anchor, here I simply modify the hash property of the current window’s location. This is the pre­

ferred, cleaner method.

If you attempt to read back the wi n d o w . 1 ocati on .hash property in an added line of script, however, the window’s actual URL probably will not have been updated yet, and the browser will appear to be giving your script false information. To prevent this problem in subsequent statements of the same function, construct the URLs of those statements from the same variable values you use to set the window.location.hash property— don’t rely on the browser to give you the values you expect.

host

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 1E4 IE5 IE5.5

C om pa tib ility / / / / / /

Example

Use the documents in Listings 17-2 through 17-4 as tools to help you learn the values that the various wi ndow. 1 o c a t i on properties return. In the browser, open the file for Listing 17-2. This file creates a two-frame window. The left frame contains a temporary placeholder (Listing 17-4) that displays some instructions. The right frame has a document (Listing 17-3) that enables you to load URLs into the left frame and get readings on three different windows available: the parent window (which creates the multiframe window), the left frame, and the right frame.

Listing 17-2: Frameset for the Property Picker

<HTML>

<HEAD>

<T IT LE >w in do w.1ocation Properties</TITLE>

</HtA0>

<FRAMESET C0LS=''50%,50%" BORDER“ 1 B O RD ER CO LO R="bl ack">

<FRAME NAME="Framel" S R C = "1s 1 17-04.htm">

<FRAME N A M E = ”Frame2" SRC="lstl7-03.htm">

</FRAMESET>

</HTML>

w /W ow O A /ecf.location.host

2 0 8 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

Listing 17-3: Property Picker

<HTML>

<HEAD>

<TITLE>Property Picker</TITLE>

<SCRIPT LANGUAGE-"JavaScript”>

var isNav4 = (navigator.appName == "Netscape" &&

navigator.appVersion.charAt(O) >= 4) ? true : false function fillLeftFrame() {

newURL = prompt("Enter the URL of a document to show in the left frame:","") if (newURL != null && newURL != "") {

parent.frames[0].location = newURL )

function showLocationData(form) { for (var i - 0; i <3; 1++) {

if (form.whichFrame[i].checked) {

var windName = form.which Frame[i ].value break

) )

var theWind = ” + windName + ".location”

if (isNav4) {

netscape.security.PrivilegeManager.enablePrivilegei"Uni versa 1 BrowserRead") }

var theObj = eval(theWind) form.windName.value = windName form.windHash.value = theOtj.hash form.windHost.value = theObj.host

form.windHostname.value = theObj.hostname form.windHref.value = theObj.href

form.windPath.value - theObj.pathname form.windPort.value = theObj.port

form.windProtocol.value = theObj.protocol form.windSearch.value = theObj.search if (isNav4) {

netscape.security.PrivilegeManager.disablePrivilegei"Uni versa 1 BrowserRead") )

}

</SCRIPT>

</HEAD>

<B0DY>

Click the "Open URL" button to enter the location of an HTML document to display in the left frame of this window.

<FORM>

< INPUT TYPE="button" NAME="operer" VALUE="Open URL..."

onClick="fi11LeftFrame()">

<HR>

<CENTER>

Select a window/frame. Then click the "Show Location Properties" button to view each window.location property value for the desired window.<P>

w/nt/oivOft/ecf. location, host

Chapter 3 ♦ Location and History Objects (Chapter 17) 2 0 9

CINPUT TYPE="radio" NAME="whichFrame" VALUE="parGnt" CHECKED>Parent window

< INPUT TYPE="radio" NAME="whichFrame" VALUE="parent.frames[0]">Left frame

< INPUT TYPE="radio" NAME="whichFrame" VALUE="parent.frames[l]">This frame

<P>

< INPUT TYPE="button" NAME="getFroperties” VALUE="Show Location Properties"

onClick="showLocationDataithis .form)">

< INPUT TYPE="reset" VALUE="C1 e a r " X P >

<TABLE B0RDER=2>

< T R X T D ALIGN=right>Window:</TDXTDXINPUT TYPE="text" NAME="windName"

S I Z E = 3 0 X / T D X / T R >

< T R X T D ALIGN=right>hash:</TD>

< T D X I N P U T TYPE="text" NAME="windHash" S I Z E = 3 0 X / T D X / T R >

< T R X T D ALIGN=right>host:</TD>

< T D X I N P U T TYPE=”text" NAME="windHost" S I Z E = 3 0 X / T D X / T R >

<1 R X I U ALiGN=right>hostname:</l U>

< T D X I N P U T TYPE="text" NAME=”windHostname" S I Z E = 3 0 X / T 0 X / T R >

< T R X T D ALIGN=right>href :</TD>

< T DXTEXTAREA NAME="windHref” R0WS=3 C0LS=30 WRAP="soft”>

< / T E X T A R E A X / T D X / TR >

< T R X T D ALIGN=right>pathname:</TD>

< T DXTEXTAREA NAME="windPath" R0WS=3 C0LS=30 WRAP="soft">

< / T E X T A R E A X / T D X / TR >

< T R X T D ALIGN=right>port:</TD>

< T D X I N P U T TYPE="text” NAME=”windPort" S I Z E = 3 0 X / T D X / T R >

< T R X T D ALIGN=right>protocol :</TD>

< T D X I N P U T TYPE="text" NAME=”windProtocol" S I Z E = 3 0 X / T 0 X / T R >

< T R X T D ALIGN=right>search:</TD>

< T DXTEXTAREA NAME="windSearch” R0WS=3 C0LS=30 WRAP="soft”>

< / T E X T A R E A X / T D X / TR >

</TABLE>

</CENTER>

</FORM>

</BODY>

</HTML>

Listing 17-4: Placeholder Document fo r Listing 17-2

<HTML>

<HEAD>

<TITLE>Opening PIaceholder</TITLE>

Continued

windowObjectAocation.host

2 1 0 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

Listing 17-4 (continued)

</HEAD>

<B0DY>

Initial placeholder. Experiment with other URLs for this frame (see right).

</BODY>

</HTML>

Figure 3-1 shows the dual-frame browser window with the left frame loaded with a page from my Web site.

[ỉ*, w in d o w .lo c a tio n P ro p e rtie s - N e ts c a p e 6 {B u ild ID : 2 0 0 0 0 8 0 7 1 2 } Rle Edit View Search Go Bookmarks Tasks Help

0 -filsttf-œ.htm ▼ S e a rc h IIs

Computer Press Association Book Awards

Best Product Specific Book (1987) The C omplete H y p erC ard H andbook Best Product Specific Book (1988):

Danny G oodman's H y p erC ard D eveloper's G itde Best Introductory How-To Book, Systems '1992).

Danny G oodman's M acintosh H andbook

Commercial Software

Focal Point (personal information manager for M ac) (1 9 8 7 , Actvision)

Focal Point ET (1 9 8 8 , Activision)

Business Class (interactive w orld travel information) (1987, Activision)

Sharp Wizard-to-Macintosh Link (1989, Sharp Electronics C orp.)

U i.-n n > P n > + < A - . t - t - . - I ..0 0 __i~1/\n<-ar,it r w

Click the "Open URL" button to enter the location o f an

| H TM L docum ent to display in the left frame o f this wmdow.

Open URL . |

Select a window/frame. Then click the "Show Location Properties" button to view each window.location property

value for the desired window JParent w indow # Left frame JThis frame

Show Location Properties Clsar

Window. j p a r e n c . f ra ro e s [0 ]

hasteI^C om puter P r e s s A s s o c i a t i o n Boc host. |www. d a n n y g . com

hostname. |umu . d a n n y g . com

h ref

h ttp ://W W W .d a n n y g .c o m /c r e d it3 . h tr

ô ! ■ 1 1- - J ______

/ c r e d i t s . h tm l Document: Done (1.16 secs)

Figure 3 -1: Browser window loaded to investigate window.location properties For the best results, open a URL to a Web document on the network from the same domain and server from which you load the listings (perhaps your local hard disk). If possible, load a document that includes anchor points to navigate through a long document. Click the Left frame radio button, and then click the button that shows all properties. This action fills the table in the right frame with all the avail­

able l o c a t i o n properties for the selected window. Figure 3-2 shows the complete results for a page from my Web site that is set to an anchor point.

windowObject.location.host

Chapter 3 ♦ Location and History objects (Chapter 17) 211

W indow p a re n t .freu nes[0]

hash. ^Computer P r e s s A s s o c ia t io n Boc host WWW. dan nyg. com

hostname WWW. dan nyg. com

href

h ttp :/ / WWW. d a n n y g .c o m / c re d its . h^r

- til ằ

pathname

/ c r e d it s .h t m l

port protocol

f i

search' h tt p :

Figure 3 -2 : Readout of all window.location properties fo r the left frame

Attempts to retrieve these properties from URLs outside of your domain and server result in a variety of responses based on your browser and browser version.

NN2 returns null values for all properties. NN3 presents an “access disallowed”

security alert. With codebase principals turned on in NN4 (see Chapter 46 of the JavaScript Bible), the proper values appear in their fields. IE3 does not have the same security restrictions that Navigator does, so all values appear in their fields. But in IE4+, you get a “permission denied” error alert. See the following discussion for the meanings of the other listed properties and instructions on viewing their values.

hostname

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

C om pa tib ility / / / / / /

Example

See Listings 17-2 through 17-4 for a set of related pages to help you view the host­

name data for a variety of other pages.

href

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

C om pa tib ility / / / / / /

w/nc/oivOA/ecf.location.href

2 1 2 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

Example

Listing 17-5 includes the unescape ( ) function in front of the part of the script that captures the URL. This function serves cosmetic purposes by displaying the pathname in alert dialog boxes for browsers that normally display the ASCII- encoded version.

Listing 17-5: Extracting the Directory o f the Current Document

<HTML>

<HEAD>

<TITLE>Extract pathname</TITLE>

<SCRIPT LANGUAGE-"JavaScript'^

// general purpose function to extract URL of current directory function getDirPath(URL) {

var result = unescape(URL.substring(0,(URL.lastlndexOf("/")) +

return result l

1))

// ) handle button event, passinc work onto general purpose function function showOirPath(URL) (

al ert(getDi rPath(URL))

|

</SCRIPT>

</HEAD>

<B0DY>

<F0RM>

<INPUT TYPE="button" VALUE="View directory URL"

onClick="showDi rPath(wi ndow.locati o n .href)">

</F0RM>

</B0DY>

</HTML>

pathname

NN2 NN3 NN4 NN6 IE3/JT IE3/J2 IE4 IE5 IE5.5

C om pa tib ility / / / / / / / / /

Example

See Listings 17-2 through 17-4 earlier in this chapter for a multiple-frame example you can use to view the location.pathname property for a variety of URLs of your choice.

w/fltfowOA/ecf.location.pathname

port

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

C om pa tib ility / / / / /

Chapter 3 ♦ Location and History Objects (Chapter 17)

Example

If you have access to URLs containing port numbers, use the documents in Listings 17-2 through 17-4 to experiment with the output of the location.port property.

protocol

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

C om pa tib ility / / / / / /

Example

See Listings 17-2 through 17-4 for a multiple-frame example you can use to view the 1 ocati on .protocol property for a variety of URLs. Also try loading an FTP site to see the location.protocol value for that type of URL.

search

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

C om pa tib ility / / / / / / / / /

Example

As mentioned in the opening of Chapter 16 of the JavaScript Bible 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 content 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 content pages where a script checks whether the page is loaded inside a frameset. If the frameset is missing, then a search string is composed and appended

213

windowObjectAocation.search

2 1 4 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

to the URL for the framesetting document. The framesetting document has its own short script that looks for the presence of the search string. If the string is there, then 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 g e t S e a r c h A s A r r a y ( ) function is more complete 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 namel=val uel&name2=val ue2&et c. ) 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 g e t S e a r c h A s A r r a y ( ) 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 LANGUAGE“ "JavaScript">

// Convert location.search into an array of values // indexed by name.

function getSearchAsArray() {

var minNav3 = (navigator.appName == "Netscape" &&

parselntinavigator.appVersion) >= 3)

var minIE4 = (navigator.appName.indexOf("Microsoft” ) >= 0 &&

parselntinavigator.appVersion) >= 4)

var minDOM = minNav3 || mirIE4 // baseline DOM required for this function var results = new A r r a y O

if (minDOM) {

var input = un escapedocation.search.substr(l)) if (input) {

var srchArray = input.split("&") var tempArray = new A r r a y O

for (var i = 0; i < srchArray.length; i++) { tempArray = srchArray[i].split("=") results[tempArray[0]] - tempArray[l]

} 1 )

return results }

function loadFrameO ( if (location.search) {

var srchArray = getSearchAsArray() if (srchArray["content"]) {

sel f.content. 1 ocatlon. href = srchArray[''content"]

) ) )

</SC RIPT>

</HEAD>

windowObjectAocation.search

Chapter 3 ♦ Location and History Objects (Chapter 17) 2 1 5

<FRAMESET C0LS="250,*" onLoad="l oadFrame() ">

<FRAME NAME="toc" SRC="1stl7-07.htm">

<FRAME NAME="content" SRC="lstl7-08.htnT>

</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 o f Contents

<HTML>

<HEAD>

<TITLE>Table of Contents</TITLE>

</HEAD>

<B0DY BGC0L0R-'#eeeeee">

<H3>Table of Contents</H3>

<HR>

<UL>

< L I X A HREF="1stl7-08.htm" TARGET="content">Page 1< /AX / L I >

< L I X A HREF="1stl7-08a.htm" TAF.GET="content">Page 2< /AX /LI>

< L I X A HREF="1stl7-08b.htm" TAF.GET="content">Page 3< /AX / L I >

</UL>

</B0DY>

</HTML>

Listing 17-8 shows one of the content pages. As the page loads, the

checkFramesetO function is invoked. If the window does not load inside a frame- set, then the script navigates to the framesetting page, passing the current content URL as a search string. Notice that for browsers that support the l o c a t i o n ,

repl ace ( ) 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.

Listing 17-8: A Content Page

<HTML>

<HEAD>

<TITLE>Page 1</TITLE>

<SCRIPT LANGUAGE“ ”JavaScript">

function checkFramesetO {

var minNav3 = (navigator.appName ~ "Netscape" &&

parselnt(navigator.appVersion) >= 3)

var minIE4 = (navigator.appName.indexOf("Microsoft") >= 0 &&

parselnt(navigator.appVersion) >= 4)

Continued

windowObjectAocation.search

216 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

Listing 17-8 (continued)

var minDOM = minNav3 || mirIE4 // baseline DOM required for this function var isNav4 = (navigator.appName == "Netscape" &&

parselnt(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.innerMidth == 0) {

return )

if (minDOM) I

// Use rep laceO tc keep current page out of history

1 oca t ion. repl ace( "1st 17-06. htm?content=" + esca ped ocati o n . href)) ) else (

location.href = " lstl7-06.htm?content=" + escape(location.href) )

) }

I I Invoke the function checkFrameset()

</SCRIPT>

</HEAD>

<ES0DY>

<Hl>Page 1</H1>

<HR>

</B0DY>

</HTML>

In practice, I recommend placing the code for the checkFrameset() function and call to it inside an external . j s library and linking that library into each content doc­

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

Methods

rel oad( unconditionalGETBoolean)

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

C om pa tib ility / / / / / /

Example

To experience the difference between the two loading styles, load the document in Listing 17-9. Click a radio button, enter some new text, and make a choice in the SELECT object. Clicking the Soft Reload/Refresh button invokes a method that

w/ntfowO A/ecf.location.reloadQ

Một phần của tài liệu tài liệu hướng dẫn sử dụng javascript (Trang 304 - 364)

Tải bản đầy đủ (PDF)

(631 trang)