?? ch07_04.htm
字號:
<?label 7.4. Bookmarklets?><html><head><title>Bookmarklets (CGI Programming with Perl)</title><link href="../style/style1.css" type="text/css" rel="stylesheet" /><meta name="DC.Creator" content="Scott Guelich, Gunther Birznieks and Shishir Gundavaram" /><meta scheme="MIME" content="text/xml" name="DC.Format" /><meta content="en-US" name="DC.Language" /><meta content="O'Reilly & Associates, Inc." name="DC.Publisher" /><meta scheme="ISBN" name="DC.Source" content="1565924193L" /><meta name="DC.Subject.Keyword" content="stuff" /><meta name="DC.Title" content="CGI Programming with Perl" /><meta content="Text.Monograph" name="DC.Type" /></head><body bgcolor="#ffffff"><img src="gifs/smbanner.gif" alt="Book Home" usemap="#banner-map" border="0" /><map name="banner-map"><area alt="CGI Programming with Perl" href="index.htm" coords="0,0,466,65" shape="rect" /><area alt="Search this book" href="jobjects/fsearch.htm" coords="467,0,514,18" shape="rect" /></map><div class="navbar"><table border="0" width="515"><tr><td width="172" valign="top" align="left"><a href="ch07_03.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0" /></a></td><td width="171" valign="top" align="center"><a href="index.htm">CGI Programming with Perl</a></td><td width="172" valign="top" align="right"><a href="ch08_01.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0" /></a></td></tr></table></div><hr align="left" width="515" /><h2 class="sect1">7.4. Bookmarklets</h2><p>We'll end this chapter with a much less common use of<a name="INDEX-1633" /><a name="INDEX-1634" />JavaScript:<em class="emphasis">bookmarklets</em>. Bookmarklets are JavaScript<a name="INDEX-1635" />URLs that have been saved asbookmarks. The basic concept behind bookmarklets has been aroundsince JavaScript was first created, but it has been slowly growing inpopularity since Steve Kangas first coined the term<em class="firstterm">bookmarklet</em> and created a web site devoted tothem at <a href="http://www.bookmarklets.com/">http://www.bookmarklets.com/</a>. Many peopleconsider bookmarklets a novelty, but they have a much greaterpotential. Bookmarklets really shine when they are combined withcustom CGI scripts, which is why they are of interest to us.</p><a name="ch07-10-fm2xml" /><div class="sect2"><h3 class="sect2">7.4.1. Bookmarklet Basics</h3><p>First, let's see how bookmarklets work. Bookmarklets are mucheasier to show than to explain, so let's look at theworld's most popular program, "Hello World," as abookmarklet. The source for it is as follows:</p><blockquote><pre class="code">javascript:alert("Hello world!")</pre></blockquote><p>If you were to type this into your browser as a location, it woulddisplay the alert shown in <a href="ch07_04.htm#ch07-68588">Figure 7-4</a>.</p><a name="ch07-68588" /><div class="figure"><img width="368" src="figs/cgi2.0704.gif" height="105" alt="Figure 7-4" /></div><h4 class="objtitle">Figure 7-4. Result from our "Hello World" bookmarklet</h4><p>You can enter this directly into your browser because this simpleprogram is also a valid URL. The <em class="emphasis">javascript</em> scheme tells browsers, whichsupport it, that they should interpret the rest of the URL asJavaScript code in the context of the current web page and return theresult as a new web page. You can also create hyperlinks that havethis format. If you were to embed the following into an HTML webpage, then you could click on the link to get the alert as well:</p><blockquote><pre class="code"><A HREF='javascript:alert("Hello world!")'>Run Script</A></pre></blockquote><p>However, neither of these examples are actually bookmarklets untilyou save the URL as a bookmark in your <a name="INDEX-1636" />browser. Doing so isbrowser-specific, of course. Most browsers allow you to click on ahyperlink with your right mouse button and choose an option to savethe link as a bookmark. Once you have done this, you have capturedthe script as a bookmarklet that you can run whenever you want bychoosing it from your list of bookmarks.</p><p>Let's look at a more complicated example. We have referencedRFCs several times thus far. Let's make a bookmarklet thatallows you to look up a particular RFC. In this case,<a name="INDEX-1637" /> <a name="INDEX-1,638" />we'll use <a href="http://www.faqs.org/rfc/">http://www.faqs.org/rfc/</a> as the RFCrepository.</p><p>Here is how we might write the JavaScript for this:</p><blockquote><pre class="code">rfcNum = prompt( "RFC Number: ", "" );if ( rfcNum == parseInt( rfcNum ) ) open( "http://www.faqs.org/rfc/" + rfcNum + ".html" );else if ( rfcNum ) alert( "Invalid number." );</pre></blockquote><p>We ask the user for an RFC number. If the user enters an integer, weopen a new browser window to fetch the corresponding RFC. Note thatwe don't handle the case in which the RFC doesn't exist;the user will simply get a 404 error from the www.faqs.org web server. However, if the userenters a value that isn't a number, we do report that error tothem. If the user enters nothing or clicks Cancel, we do nothing.</p><p>Now let's convert to this to a bookmarklet. First, we must needto make sure we do not return any values from our code. If the codein your bookmarklet returns a value, some browsers (includingNetscape's) will replace the current page with the value. Youwill confuse users if, for example, they get an empty page with a<tt class="literal">[null]</tt> in the top left corner every time they useyour bookmarklet. The easiest way to avoid returning a value is touse the <tt class="function">void</tt> function. It takes any value as anargument and returns nothing. We can wrap the<tt class="function">void</tt> function around the last statement thatreturns a value, or simply append it to the end. We'll do thelatter because in this script there are three different lines thatcould be executed last, depending on the user's entry. So weadd the following line to the end of our script:</p><blockquote><pre class="code">void( 0 );</pre></blockquote><p>Next, we <em class="emphasis">should</em> need to remove or encode anycharacters that are not valid within a URL. This includes whitespaceand the following characters: <tt class="literal"><</tt>,<tt class="literal">></tt>, <tt class="literal">#</tt>, <tt class="literal">%</tt>,<tt class="literal">"</tt>, <tt class="literal">{</tt>, <tt class="literal">}</tt>,<tt class="literal">|</tt>, <tt class="literal">\</tt>, <tt class="literal">^</tt>,<tt class="literal">[</tt>, <tt class="literal">]</tt>,<tt class="literal">`</tt>.<a href="#FOOTNOTE-11">[11]</a> However,<a name="INDEX-1639" /><a name="INDEX-1640" /><a name="INDEX-1641" />NetscapeCommunicator 4.x will not recognize encoded syntax elements (such asbrackets) within JavaScript URLs. So although it means thatbookmarklets containing these characters are invalid URLs, if youwant your bookmarklets to work with Netscape's browsers, youmust leave these characters unencoded. Other browsers accepts thesecharacters encoded or unencoded. In any event, you should remove anyunnecessary whitespace.</p><blockquote><a name="FOOTNOTE-11" /><p>[11]Control and non-ASCIIcharacters are invalid as well, but these values must be escapedwithin JavaScript anyhow. Also, you may notice that this list isdifferent than the list provided in <a href="ch02_01.htm#ch02-80730">Section 2.1.3, "URL Encoding"</a>.That list is for HTTP URLs, so it includes characters that havespecial significance to HTTP. JavaScript URLs are different than HTTPURLs, so this list includes only characters considered illegal forall URLs.</p></blockquote><p>Finally, we prefix our code with <tt class="literal">javascript:</tt>, andwe get the following:</p><blockquote><pre class="code">javascript:rfcNum=prompt('RFC%20Number:','');if(rfcNum==parseInt(rfcNum))open('http://www.faqs.org/rfc/'+rfcNum+'.html');else if(rfcNum)alert('Invalid%20number.');void(0);</pre></blockquote><p>The line endings are not part of the URL but have been added to allowit to fit on the page.</p><p>There is one more thing that you should keep in mind when workingwith bookmarklets. Bookmarklets execute in the same scope as thefrontmost page displayed in the user's browser. This has anumber of advantages as we will see in the next section, <a href="ch07_04.htm#ch07-53404">Section 7.4.2, "Bookmarklets and CGI"</a>. The disadvantage is that you must becareful that the code you create does not conflict with other codethat is on the current page. You should be especially careful withvariable names and create names that are very unlikely to appear onother web sites.<a name="INDEX-1642" /> <a name="INDEX-1,643" />Variables are case-sensitive inJavaScript; using odd combinations of capitalization in variables isa good idea. In our last example, <tt class="literal">rFcNuM</tt> may havebeen a better (though less readable) choice as a variable name.</p><a name="ch07-42535" /><div class="sect3"><h3 class="sect3">7.4.1.1. Compatibility</h3><p>Because <a name="INDEX-1644" /> <a name="INDEX-1,645" />bookmarklets use JavaScript, theyare not compatible with all web browsers. Some browsers that supportJavaScript, such as<a name="INDEX-1646" />Microsoft Internet Explorer 3.0 donot support bookmarklets. Other browsers impose limitations onbookmarklets. Unless you're distributing your bookmarklets asunsupported novelties, you should do extensive testing. Bookmarkletsuse JavaScript in a less than traditional manner, so test them withas many different versions of as many different browsers on as manydifferent platforms as you can.</p><p>You should also keep your bookmarklets short. Some browsers do notimpose a limit on the length of a URL; others limit URLs to 255characters. This can even vary by platform: for example, Communicator4.x allows only 255 characters on MacOS while it allows much longerURLs on Win32.</p><p>One of the features that some users of bookmarklets promote is thatbookmarklets avoid some of JavaScript's browser incompatibilityissues. Because Netscape and Microsoft have different implementationsof JavaScript, if you want to create a bookmarklet that usesincompatible features of each, you can create two differentbookmarklets instead of one bookmarklet that attempts to support bothbrowsers. Then people can choose the bookmarklet that is appropriateto their browser. The problem with this approach is that Netscape andMicrosoft are not the sole distributors of web browsers. Although
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -