Using HTML Forms With AppleScripts

What if you could use an HTML form in place of an AppleScript dialog box?

AppleScript dialogs are terribly limited, which often forces a scripter to chain together a dizzying series of sequential dialogs and alerts. The alternatives either require additional software, or to tackle XCode and the newer and more complicated AppleScript Studio.

But thanks to AppleScript’s ability to take advantage of URL handlers, you can use an HTML form to pass values to your AppleScript.

Rather than try to explain it in too much detail, I’ve attached a demonstration to download and try out. This is an application that writes a simple “thank you” letter to a relative. Just open it to run the script. You can fill out a form to create the letter, and then you can just click links to have the letter read out loud, edit in in TextEdit, or erase it and start over.

Under the hood, what’s happening is:

1. The applet registers the “thankyou://” URL scheme

3. It opens up an HTML page in it’s bundle’s resources folder. The HTML page sends requests using “thankyou://” URLs (the form is sending a GET request, so it does the same)

4. The applet receives these events, parses the URL, and then acts on them depending on the “location” of the URL

The first step is well documented at MacOSXAutomation.com. Step 2 is straightforward HTML form building and a little AppleScript in the “run” handler to open the bundled HTML file. The last step is straight AppleScript, using an “open location” handler to receive and parse the incoming URL.

The parsing is the really tricky part, but as luck would have it, I’ve taken care of this for you.

If you open the script in AppleScript Editor, you can see the bundle contents and take the script apart. The complicated part is the “newURI()” handler and associated script object. It breaks down the “thankyou://write?n=Jimmy…” style URL into an object with useful properties, such as location and a record set of arguments. This handler can be pulled unmodified from this script and put into your own applications – it’s entirely agnostic as to the URL scheme or individual arguments it receives.

The rest is just taking the properties of that object and passing them to an if/else tree that checks the “location” of the URL and acts accordingly.

This is, of course, a frivolous example, but it demonstrates how powerful a tool this can be. With a little more complexity on the HTML side of things, a little javascript could work to pull in data from other sources, create more dynamic forms, and provide up-front data validation.

The one limitation of this method, compared to traditional dialog boxes, is that you cannot put any forms in-line with the script’s execution. But for scripters who just want some up-front configuration, this can be a very flexible tool.

If you have any comments or feedback on this, sound off in the MacScripter forums.

Twitter, Facebook

Written on October 21, 2010