Using AppleScripts in your app

AppleScript is the macOS system-level scripting language than can be used to control applications. You can create AppleScripts using the AppleScript Editor.

In order for Xojo to run an AppleScript, the script must be saved as a “compiled” script. You can do this using the Script Editor and selecting Compile on the toolbar and saving the script.

Now you can use the AppleScript with Xojo by dragging the compiled script onto the Navigator. The script appears in the Navigator with a script icon next to it. This item is added to Xojo as an “external” item and includes it with the application when you build.

To run the AppleScript, just call it by the name it has in the Navigator.

Here is a simple script that you can compile and drag into your project to launch iTunes:

tell application "iTunes"
  launch
end tell

Passing parameters

To pass parameters, add an “on run” handler to contain your script and specify the parameters using curly brackets:

on run {value1, value2}
  // your script code goes here
end run

Xojo Integers passed to AppleScripts are sent as Integer values and are treated as Integers by AppleScript. All other Xojo types (including other numeric types such as Int8 and Double) are sent as Strings and are treated as Strings by AppleScript.

Returning values

You can also return values from an AppleScript back to your Xojo code by using the return command in the script. This example adds two values and returns the result:

on run {value1, value2}
  return value1 + value2
end run

AppleScript does not use types like Xojo does. All values are returned as Strings to Xojo.

Calling AppleScripts from Xojo

AppleScripts are called just like built-in global methods and functions. You use the name it has in the Navigator. If it has parameters, you supply them after the name as you would any other method that has parameters.

Scripts that return values can be assigned to a Xojo variable. This command calls the above script that adds two values:

Var sum As String
sum = Add(5, 10)

Note: If there is an error in your AppleScript, it is logged to the Messages panel at runtime.

Restrictions

In order to use AppleEvents on newer versions of macOS (Mojave and later) you may need to include the NSAppleEventsUsageDescription key in your plist file.

More information here:

AppleEvents

AppleEvents are a way for macOS apps to communicate with one another. An AppleEvent is a self-contained block of data which consists of a sequence of key-type-value data (called an AppleEvent Descriptor, or AEDesc). Each descriptor can contain other descriptors as an ordered array or as a mixture of keyed data.

The AppleEvent as a whole is both itself and the AppleEvent Descriptor.

See also