Section 9.2. Safari


9.2. Safari

For years, Microsoft was the dominant company in Mac Internet programs. Internet Explorer (IE), Microsoft's Netscape-devouring Web browser, came preinstalled on all Macs, and with good reason: for a while, IE was the fastest, least crash-prone Web browser available on the Mac.

However, as time went on, Microsoft slowed down development on Internet Explorer for Mac. Other Web browsers began to join the crowd: OmniWeb, Mozilla, Camino (formerly known as Chimera), Opera, and other similarly strange-named programs. Soon Apple decided to join the party, with its own browser named Safari. With emphasis on speed and simplicity, Safari quickly eclipsed Internet Explorer as a favorite of Mac fans worldwide. In fact, more than a million people downloaded Safari within the first two weeks of its existence.

9.2.1. Opening Web Sites

The simplest thing you can do with any Web browser is, of course, load a Web site. Thanks to AppleScript, however, you can load multiple Web sites, automatically and without fuss, by commanding Safari. That way, you can use AppleScript to load all your favorite Web sites as you're eating breakfast and come back to find all your pages just waiting to be read.

Here's how:

tell application "Safari"     activate     open location "http://www.apple.com/"     open location "http://www.apricot.com/"     open location "http://www.banana.com/" end tell

The open location command lets you tell Safari what sites to load; if you have multiple open location commands, Safari will load multiple pages for you. (As described on Sidebar 9.5, open location has a number of other Internet-related uses as well.)

9.2.1.1 Opening Web sites within the same window

The trouble with your current script is that Safari loads each Web site in a separate windowa recipe for massive screen clutter. The problem gets even worse if you add extra open location commands to the script, since Safari will have to open even more windows to load your Web sites.

Luckily, Safari has a helpful feature, called tabbed browsing, to cut down on this window overload. When you turn on tabbed browsing (in Safari Preferences Tabs), you get to open multiple Web sites within the same window, with each site getting its very own "tab" at the top of the window. That way, you can browse your favorite 10 Web sites without opening 10 separate windows.

Frequently Asked Question
Scripting Other Browsers

I use a Web browser besides Safari. Am I left out of the AppleScript party?

If you visit banking or gaming Web sites a lot, you might prefer to use a more widely compatible browser than Safari. Or, if you're just the power-user type, Safari might not give you the features you crave. Either way, there are plenty of alternative Web browsers.

Depending on the browser you choose, though, you'll get a much different dose of AppleScript control. Every Web browser supports the open location command (Sidebar 9.5), but beyond that, the differences are huge. Here are your options:

  • OmniWeb (www.omnigroup.com/applications/omniweb/) is just about the most powerful Web browser money ($30) can buy. Its powerful workspaces feature, for instance, lets you cluster your favorite Web sites into specific windows. Even better, OmniWeb has the sort of AppleScript control that would make even Safari blush: the check command (for seeing if one of your Favorites has changed since the last time you visited the page) and the bookmark class (for creating your own Favorites from AppleScript) are just a couple examples.

  • Internet Explorer (www.microsoft.com/mac/ie/) is Microsoft's Web browser. Since it hasn't been updated in a few years (and won't be updated ever again for the Mac), it's missing a lot of Safari's features: pop-up blocking, tabs for different sites within one window, and so on. Still, if you use Internet Explorer for compatibility with certain Web sites, you'll be happy to know that it has its own complete scripting dictionary to rival Safari's.

  • iCab (www.icab.de) is a sort of souped-up Internet Explorer. In other words, it supports all the AppleScript commands that Internet Explorer doesand a few more. If scriptability is important to you, you'll be glad to know that iCab supports such useful commands as cancel progress (for stopping downloads) and enter kiosk mode (for browsing the Web full-screen).

  • Mozilla (www.mozilla.org/products/mozilla1.x/) is a complete Web-browsing, email-reading, carpet-cleaning programthe Microsoft Office of Web browsers. Unfortunately, its complete feature set doesn't extend to its AppleScript support; its abysmal dictionary supports only four commandsand unhelpful ones at that.

  • Netscape (www.apple.com/downloads/macosx/internet_utilities/netscape.html) is essentially a copy of Mozilla with a different look. Its AppleScript support is also identical to Mozilla'sthat is to say, terrible.

  • Camino (www.mozilla.org/products/camino/), another spin-off of the Mozilla project, has impressed thousands of Mac fans with its friendly, Mac-like interface. Unfortunately, Camino has no AppleScript dictionary whatsoever.

  • Firefox (www.mozilla.org/products/firefox/) is yet another spin-off of the Mozilla project. Unlike Mozilla and Netscape, however, Firefox is only a Web browserand a fast, customizable one at that. However, Firefox sadly lacks a powerful dictionary.

  • Opera (www.opera.com/download/) is a speedy, powerful, and expensive ($40) Web browser. If you're looking for AppleScript support, stay far away; Opera has none either.


Normally, you create additional tabs inside a window with the File New Tab command (-N). Then you type the URL of the page you want to open into the Address bar, and press Return to load the page. (By repeating this process, you can create additional tabs inside the same window.)

There's another timesaving way to use tabs, though. If you choose Safari Preferences General and pick "Open links from applications: in a new tab in the current window," your existing script will not only open multiple Web sites for you, but the script will open all the Web sites inside the same window. That way, when you run the script in the morning, you can come back from breakfast to find all your favorite Web sites openbut with only a single Safari window on the screen.

For even more usefulness, have Mac OS X run your favorite Web site script automatically when you log in to your Mac. (Section 2.2.2 has the directions).

9.2.2. Viewing a Site's Code

Whenever you type a URL in the Address bar and press Return, Safari goes out and fetches that site's HTML codethe instructions that tell your Web browser how to present the Web site onscreen. If you're a budding Web designer, this code (also called source) can help you understand how to build Web pages.

For example, by looking at a Web site's HTML source, you can see precisely how the Web designer laid out the page. Sometimes, you'll even find hidden notes that the Web designer embedded in the code, to remind himself why he coded something a particular way. If you have an interest in learning HTML, you ought to spend at least a little time browsing Web pages' source.

Once you've opened a page in Safari, you can examine the page's source by choosing View View Source (Option--V). The trouble is, the code is uneditable in Safari; you can page through the commands, but you can't experiment by changing them.

That's where AppleScript comes in.

If you open Safari's AppleScript dictionary and look at the Safari Suite, you'll notice that every Safari document has a source property. With this information in hand, you can write a script that copies a Web page's source to a new TextEdit document, where you can edit the code:

Of course, when you edit a Web page's source in this manner, you're actually editing a copy of the Web site; changes you make on your own computer won't take effect on the actual Web site that people visit.

--Part 1: tell application "Safari"     set pageSource to the source of the front document end tell --Part 2: tell application "TextEdit"     activate     make new document at the front     set the text of the front document to pageSource end tell

Here's how your new script works:

  • Part 1 gets the HTML source of your frontmost Safari document (Figure 9-3, top). This part of the script then puts that information into the pageSource variable.

  • Part 2 activates TextEdit, creates a new document, and places the pageSource text into it (Figure 9-3, bottom). You're left with fully editable HTML code.

If you're interested in Web design and programming, check out a Web site like www.htmlgoodies.com to learn HTML. Once you're a little more experienced, look at a book like Learning Web Design or HTML & XHTML: The Definitive Guide (both from O'Reilly) for a more thorough explanation of the various display commands that make Web sites work.

9.2.3. Viewing a Site Without Formatting

There's a time for blinking Web ads, animated corporate logos, and flashy multimedia Web pages, but there's also a time for good old text. For instance, if you're looking at a page on a small screen, all the graphics can leave you with no room to read the actual content. Therefore, when you just want to get some quick information, it can be more helpful to have just a Web site's text than to have all the visual distractions that come along with it.

That's the logic behind the following script, at least. When you run the script, Safari extracts just the text from the front-most window, and places that text into a new TextEdit document. You'll end up with a simple, uncluttered windowno buttons, no links, and most importantly, no flashy banner ads:

tell application "Safari"     set textVersion to (the text of the front document) --Gets just the text end tell tell application "TextEdit"     activate     make new document at the front     --Put the text in TextEdit     set the text of the front document to textVersion end tell

Once you've got a plain-text version of a Web site with this script, it's easier to use AppleScript with the site, too. You can run the script from Section 8.2.2.1, for example, to speak your text-only Web site out loud. Another option would be to use AppleScript to print out that text document for you, using the print the front document command directed at TextEdit. Then, on your train ride to work, you could catch up on the day's news without any of the annoying graphical fluff that usually gets printed.

Figure 9-3. Top: An open window in Safari. As it turns out, this document is no more than a series of HTML (HyperText Markup Language) commands. Bottom: Run the script and you'll be able to seeand changeyour copy of the site's source in TextEdit. Once you've modified the code to your liking, choose Format Make Plain Text, and then choose File Save. Make sure the file name ends in .html (otherwise, Mac OS X won't know that you're saving a Web page). When the Append dialog box appears, click Don't Append. Finally, navigate to your newly saved file in the Finder, and double-click it to see your changes in Safari.


9.2.4. Running AppleScripts from Safari

Script Editor is a great place to run your scripts, but you probably spend a lot more time in Safari every day than you do in Script Editor. Luckily, Safari has several different ways to run AppleScriptssome straightforward and some totally hidden. Using these convenient tricks, you won't have to flip back to Script Editor every time you feel the proverbial "tug of the AppleScript."

9.2.4.1 Scripts that appear on Web pages

If you're browsing AppleScript Web sites (like those mentioned on Section C.1), you can simply select the AppleScript code you see on a Web page and choose Safari Services Script Editor Run as AppleScript (Section 4.8.3). In the background, Script Editor runs your script, and displays any dialog boxes along the way. That's a heck of a lot faster than selecting the script on the Web page, copying it from Safari, pasting the code in Script Editor, and then running the script from there.

Power Users' Clinic
Running JavaScript Code in Safari

As described on Sidebar 3.2, JavaScript is an alternative language for controlling your Mac. More importantly, however, JavaScript is a language for automating the Web. It's what makes a Web site's buttons change color when you move your mouse over them, for example, and what lets you click the Print link on Mapquest.com to automatically bring up a Print dialog box. Even if you never write a line of JavaScript code yourself, you still use it dozens of times a day while browsing the Web.

Understanding this, Safari's programmers decided to include a special AppleScript command in Safari's dictionary: do JavaScript. When you provide that command with a line of JavaScript code (or even a few lines in a row) Safari obediently runs themeven if you haven't installed Late Night Software's (www.latenightsoftware.com) version of JavaScript for your entire Mac.

Now, a lot of what JavaScript can do in Safari is the same stuff you can do with AppleScript. For instance, if you wanted to print the current Web page, you could write either this (in pure AppleScript):

tell application "Safari"     print the front document end tell

or this (as an AppleScript/JavaScript hybrid):

tell application "Safari"     do JavaScript "window.print( )" in the front document end tell

On the other hand, there are plenty of things in Safari that you can only do with JavaScript. For instance, the following script would display a dialog box that lists every link on the current Web pagesomething impossible to do with just AppleScript:

tell application "Safari"     set theCode to "var links = document."¬     & "links;"for(var i=0;i<DEFANGED_"¬     & "links.length;i++){alert(\"Link#\"+"¬     & "(i+1)+\":\"+links[i].href);}     do JavaScript theCode in the front document end tell

If that code looks foreign to you, you're in good company; JavaScript is significantly uglier than AppleScript. If you're interested in pursuing JavaScript further, though, you can start out with something like Designing with JavaScript before moving on to a more reference-y book like JavaScript: The Definitive Guide (both books from O'Reilly).

And if you're just interested in some more code (without necessarily understanding how it works), Apple's written a number of JavaScripts just for Safari. Check out www.apple.com/applescript/safari/bookmarks.html, for example, for some useful JavaScripts that integrate Safari's features with Sherlock and iTunes.


If you want to modify a script you see on a Web page, though, you have no choice but to copy the code into Script Editor (Safari won't let you edit the text on Web pages). And while that might sound tedious, Safari's Services menu helps you out here, too. All you need to do is select the AppleScript code on the Web page and then choose Safari Services Script Editor Make New AppleScript. That command copies the AppleScript code and then pastes it into a new Script Editor window for you automatically.

From there, all you need to do is compile and run the script to test it on your Mac and then make any code tweaks as you see fit. If the script runs to your satisfaction, just save it in your favorite location (like the Library Scripts folder).

9.2.4.2 Mini-scripts in the Address bar

If there's a quick script you want to whip upsay, a single-line display dialog commandyou can type it straight into Safari's Address bar, using this format:

applescript://com.apple.scripteditor?action=new&script=yourScriptCommands

In this special kind of URL, everything before yourScriptCommands is always the same. To substitute your own code, you simply replace yourScriptCommands with whatever commands you want, like this (type it all on one line):

applescript://com.apple.scripteditor?action=new&script=display dialog "My oh my"

When you press Return in Safari's Address bar, a new Script Editor opens with your commands all written out for you. All you have to do is click Run, since Safari doesn't do that automatically (Figure 9-4).

Of course, that doesn't seem too earth-shattering. "Why don't I just type the commands directly into Script Editor?" you wonder.

As it turns out, you can use URLs in this format on your own Web pages. If you happen to maintain an online journal (or Weblog), for example, you can place an AppleScript URL like this right on a page, so that any viewers can click the link and see your code in Script Editor. In other words, the biggest benefit of AppleScript URLs isn't that you can use them on your own computerit's that you can put them on the Internet so you can share your code with other people.

If you don't feel like memorizing that complicated URL format, though, you can simply type applescript:// and press Enter to jump right to Script Editor from Safari.

Better yet, type applescript:// and don't press Enterinstead, drag the globe icon from the Address bar to your Bookmarks bar. Safari asks you to name your new bookmark (call it something creative, like "Launch Script Editor"). From then on, you can simply click your bookmark in Safari to jump right to Script Editor.

For more information about AppleScript's special URL formatincluding a script to create URLs in this formatsee www.apple.com/applescript/scripteditor/12.html.

Figure 9-4. Top: Type out your command at the end of the special AppleScript URL. If you want to run multiline commands, simply type %0D (that's a zero, not the letter O) between the commands that you want to appear on separate lines.Middle: As soon as you hit Return or Enter in the Address bar, Script Editor springs open and creates a new window for the commands you entered. Bottom: Simply click Run in Script Editor to see the results of your toil.


9.2.4.3 Saved scripts in the Favorites bar

If you've saved a script as an Application (Section 2.2.2), you can run it from Safari's Favorites bar with ease. Here's how:

  1. Find the path to the application.

    If you saved a script called Hyena as an application in your Library Scripts folder, for example, the path would be /Library/Scripts/Hyena.app.

  2. Type the path to the file into Safari's Address bar.

    To get Safari to open a file for you, use file:///(yes, that's three forward slashes, not the two you normally see after http:), followed by the path to where the file lives on your Mac. For example, the file path for the Hyena.app script would look like this:

    file:///Library/Scripts/Hyena.app

    At this point, you could press Return to open the file (and, as a result, run the script). Or you could wait a few steps, to make that script a permanent fixture of Safari's Bookmarks bar.

  3. Drag the mini-icon from Safari's Address bar into the Bookmarks bar (Figure 9-5, top).

    This is a quick way to create a new bookmark.

  4. Enter a name for your bookmark (Figure 9-5, middle).

    This is the name that will appear in your Bookmarks bar, so try not to make it too long.

Now, whenever you want to run your script from Safari, simply click the script's name in the Bookmarks bar (Figure 9-5, bottom).

If the Safari scripts in this book don't leave you satisfied, visit www.apple.com/applescript/safari/. There, you'll find many more scripts, including a script for placing browser windows side-by-side and a script for sending a link to the current Web page in a new email message.

Figure 9-5. Top: Using Mac OS X's special URL format, you can specify any file or folder on your hard drive. In this case, you enter the path to an AppleScript on your system.Middle: When you drag the URL into your Bookmarks bar, you see this dialog box. (If you'd rather the bookmark appear in your Bookmarks menu, choose Bookmarks Add Bookmark instead of dragging the URL to your Bookmarks bar.) Bottom: Now, whenever you want to run your script, simply click it once in the Bookmarks bar. Or, if you prefer, you can use the key combination listed in the Bookmarks Bookmarks Bar menu.




AppleScript. The Missing Manual
AppleScript: The Missing Manual
ISBN: 0596008503
EAN: 2147483647
Year: 2003
Pages: 150

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