Guides and Sample Code

Developer

Mac Automation Scripting Guide

Prompting for Text

Use the display dialog command’s optional default answer parameter to collect text, such as a username or email address, as your script runs. As demonstrated by Figure 23-1, Listing 23-1, and Listing 23-2, the inclusion of the default answer parameter automatically adds a text entry field to the resulting dialog. Any string you provide for the parameter appears in the text field when the dialog displays. Providing an empty string ("") produces an empty text field. When the dialog dismisses, any text from the field is returned in a text returned property of the display dialog command’s result.

Figure 23-1A dialog prompting for text input image: ../Art/dialog_promptfortext_2x.png

APPLESCRIPT

Open in Script Editor

Listing 23-1AppleScript: Prompting for text input
  1. set theResponse to display dialog "What's your name?" default answer "" with icon note buttons {"Cancel", "Continue"} default button "Continue"
  2. --> {button returned:"Continue", text returned:"Jen"}
  3. display dialog "Hello, " & (text returned of theResponse) & "."

JAVASCRIPT

Open in Script Editor

Listing 23-2JavaScript: Prompting for text input
  1. var app = Application.currentApplication()
  2. app.includeStandardAdditions = true
  3. var response = app.displayDialog("What's your name?", {
  4. defaultAnswer: "",
  5. withIcon: "note",
  6. buttons: ["Cancel", "Continue"],
  7. defaultButton: "Continue"
  8. })
  9. // Result: {"buttonReturned":"Continue", "textReturned":"Jen"}
  10. app.displayDialog("Hello, " + (response.textReturned) + ".")

Prompting for Hidden Text

Protect potentially sensitive information from prying eyes by using the display dialog command’s default answer parameter in conjunction with the hidden answer parameter to show bullets instead of plain text in the dialog’s text field. See Figure 23-2, Listing 23-3, and Listing 23-4.

Figure 23-2A dialog prompting for hidden text input image: ../Art/dialog_promptforhiddentext_2x.png

APPLESCRIPT

Open in Script Editor

Listing 23-3AppleScript: Prompting for hidden text input
  1. display dialog "Please enter a passphrase to use this script." default answer "" with icon stop buttons {"Cancel", "Continue"} default button "Continue" with hidden answer
  2. --> Result: {button returned:"Continue", text returned:"MySecretPassphrase"}

JAVASCRIPT

Open in Script Editor

Listing 23-4JavaScript: Prompting for hidden text input
  1. var app = Application.currentApplication()
  2. app.includeStandardAdditions = true
  3. app.displayDialog("Please enter a passphrase to use this script.", {
  4. defaultAnswer: "",
  5. withIcon: "stop",
  6. buttons: ["Cancel", "Continue"],
  7. defaultButton: "Continue",
  8. hiddenAnswer: true
  9. })
  10. // Result: {"buttonReturned":"Continue", "textReturned":"MySecretPassphrase"}