"end if"/"else if" in AppleScript not working? - macos

I am trying to code an AppleScript with a dialog box that has multiple buttons, which each execute different commands. My problem is that AppleScript Editor detects either "end if" or "else if" as a syntax error, as per the title.
For example:
set dialog to display dialog "Test" buttons {"1","2"}
set pressed to button returned of dialog
if pressed is equal to "1" then activate "Safari"
else if pressed is equal to "2" then beep
end if
AppleScript Editor displays the error "Syntax Error: Expected end of line, etc. but found “else if”."
Is there something I'm doing wrong?

AppleScript's conditionals have two formats, a simple single-line format:
if condition then statement
and a multiline format:
if condition then
statement
end if
If you want to use multiple statements or have multiple conditions (else if), you must use the multiline format:
set dialog to display dialog "Test" buttons {"1", "2"}
set pressed to button returned of dialog
if pressed is equal to "1" then
activate "Safari"
else if pressed is equal to "2" then
beep
end if

Related

How to pass variable from AppleScript to Automator?

I'm looking for assistance with passing a variable from AppleScript to Automator.
I am working on a small automator app. I need to type a number that will be added to the end of a PDF's name. I used "Ask for text" in automator, however, I found out that, first, the pop-up window does not stay at the centre of screen. (27" iMac.), and second, every time after I input a number, I need to use mouse to click OK, the Enter key does not work.
So I turned to AppleScript for help. And here is what I found, a window that let me input the number, then click continue, then pass the number to Automator to add to PDF's name.
Set Value of Variable to storage
Run AppleScript: Ignore this action's input.
on run {input, parameters}
display dialog "Please enter QC Round." default answer "" with icon stop buttons {"Cancel", "Continue"} default button "Continue"
--> Result: {button returned:"Continue", text returned:"MySecretPassphrase"}
return input
end run
Set Value of Variable to Continue
Get Value of Variable to Storage
Rename Finder Items: Add Text
Add:_QC_Continue(Variable) after name
But it does not work. Can anyone help me fix it?
In Automator, an action gets its input from the previous action, and passes its results on to the next action. In a Run AppleScript action, the input is in the input argument to the run handler, and items returned by the handler are what get passed on.
In your example, you are just passing on the input, which doesn't have a value since the action is ignoring its input. The solution is to return the text from the dialog, for example:
on run {input, parameters}
set dialogResult to (display dialog "Please enter QC Round." default answer "" with icon stop buttons {"Cancel", "Continue"} default button "Continue")
return text returned of dialogResult
end run

Applescript code messy, how to fix

display dialog "Play Nillys Realm?" buttons {"Yes please", "No"} default button 1
if result = {button returned: "Yes please"} then
display dialog "Long time loading, u think?" buttons {"Yes", "No"}
end if
if result = {button returned:"No"} then
tell application "Google Chrome"
repeat 5 times
open location "http://test.nillysrealm.com"
activate
end repeat
if result = {button returned:"Yes"} then
tell application "Google Chrome"
repeat 10 times
open location "http://test.nillysrealm.com"
activate
end repeat
thats my code and it is a MESS. Can anyone help me fix? It will never load
It is not easy to help in your script, because reading it, I do not understand what you want to do. However you are not using the 'Result' variable correctly. This variable always contains the result of the last dialog, so when you have 2 dialog box, any test of that variable will always give you the result of the second dialog, never the first one.
The solution is to specifically assign the result to a separate variable, like in example bellow :
set Dialog1 to display dialog "do you agree ?" buttons {"Yes please", "No"} default button 1
if button returned of Dialog1 is "Yes please" then
-- do something here when user click "yes please"
else
-- do somthing here when user click "No"
end if

How can I handle AppleScript dialog response?

I am using a script that I wrote to automatically write my dynamic IP to a .txt file but my problem is that I cannot get the dialog to close when the quit button is clicked.
set yn to (display dialog "Your ip has been written to the server, the application will re-run in 10 minutes if you DO NOT close this window." buttons {"Quit", "Run again"} giving up after 600)
if yn is equal to "Quit" then
quit
end if
What I ended up doing was
display alert "This is an alert" buttons {"No", "Yes"}
if button returned of result = "No" then
display alert "No was clicked"
else
if button returned of result = "Yes" then
display alert "Yes was clicked"
end if
end if
You can replace the lines "display alert "No/Yes was clicked"" with whatever code you want to run
The simplest way to figure out how to make use of yn's button pressed is to look at yn:
set yn to (display dialog "Your ip has been written to the server, the application will re-run in 10 minutes if you DO NOT close this window." buttons {"Quit", "Run again"} giving up after 600)
return yn
You'll see that yn returns {button returned:"Quit", gave up:false}. This indicates that yn has a property button returned that you can use in your if statement.
Another way to figure this out is to look through the AppleScript dictionary (File > Open Dictionary...) that documents display dialog, which is the StandardAdditions dictionary.
To add as an answer as the original question had a giving up after and I needed to do something in my script if the dialog did exceed past the timeout period. Here is an additional option that considers the timeout:
set dialogTitle to "Star Wars Question"
set theDialog to display alert "Do you think Darh Maul should have his own movie?" buttons {"YES", "NO"} default button "YES" giving up after 10
if button returned of theDialog = "" then
display notification "No decision was made, cancelled dialog" with title dialogTitle
else if button returned of theDialog = "YES" then
display notification "I concur" with title dialogTitle
else if button returned of theDialog = "NO" then
display notification "I find your lack of faith disturbing" with title dialogTitle
end if
First, some notes:
Even used without assigning a variable, dialogs return a result "record" object containing two key-value pairs: button returned and gave up.
To get the selected button's text (other than Cancel), use button returned of result.
When using giving up after n, use either button returned of result (with text value of "" (empty string)) or gave up of result (with boolean value of true or false).
Clicking the "Cancel" button causes an error (number -128 or "User canceled."). To handle the Cancel button, use a try block.
In my first example, I'm providing a Cancel button in multiple places. This demonstrates that the on error code will work regardless of which dialog in the try block returns the Cancel button. If you don't need a Cancel, then just provide a single button such as buttons "OK".
I'm using parens around some text in my examples, but AppleScript does not require these. AppleScript does require quotes around text.
Tested in both Monterey and High Sierra, and using Mar10Josh's answer, with fixes, as the basis for my examples to make it simple and clear...
try
display dialog ("An example dialog.") buttons {"Cancel", "OK"} giving up after 5
if button returned of result = "OK" then
display dialog ("You clicked OK.") buttons {"OK", "Cancel"}
else if gave up of result then
display dialog ("You let the dialog expire.") buttons {"OK", "Cancel"}
end if
-- handle the Cancel button here
on error "User canceled." -- or you can say: on error number -128
display dialog ("You clicked Cancel.") buttons "OK"
end try
Same thing, stated slightly differently to show some other stuff (text without parens, giving up after option, generic error handling):
try
-- uncomment following line to see non-Cancel-related error result ;)
-- error "foobar!"
display dialog "An example dialog." buttons {"OK", "Cancel"} giving up after 5
if button returned of result = "OK" then
display dialog "You clicked OK." buttons "OK"
else if gave up of result then
display dialog "You let the dialog expire." buttons "OK"
end if
-- handle any error that might occur here;
-- errText and errNum are variable names I chose for these values
on error errText number errNum
if errText is "User canceled." then -- or you can say: if errNum is -128
display dialog "You clicked Cancel." buttons "OK"
else
display dialog "Error: " & errText & return & return & "Number: " & errNum buttons "OK"
end if
end try
display dialog ("An example dialog.") buttons {"Cancel", "OK"}
if button returned of result = "Button" then
display dialog ("You clicked Button.")
end

Input Dialog Box Reappears when it is "on idle" in Applescript

I have this functionality in my Applescript wherein a input dialog box is shown to the user to enter some text. And this dialog box code is inside "on idle" "end idle" which repeats after every 3 seconds.
The issue is when this dialog box is shown and the user doesn't enter any details and leave the dialog box open, than after a minute or so this dialog box still remains but another dialog box appears (the same one repeats). How should I handle this issue inside "on idle" anyone?
Breakup of the code is shown below for reference.
on idle
try
tell application "iTunes"
repeat
set loginbutton to display dialog "Enter your facebook log in name to start using XXX." default answer loginusername with title "XXX Log In" buttons {"Quit", "OK"} default button 2
display dialog "loginbutton = " . loginbutton
end repeat
end tell
end try
return 3
end idle
In regular AppleScript, when you put up a dialog the script will wait until the dialog is dismissed before continuing. I am not able to get the symptoms you are describing, although your example snippet is incomplete and a bit buggy - you are in a repeat (forever) loop with no means of escape, since you are also trapping all errors.
The idle handler isn't really the place for things like this - this handler is called when your application is, well, idle, so whatever code is in it will run every time the script isn't doing anything.
if you are just wanting a dialog that repeats until a correct answer is returned, you can use something like the following in your main run handler
repeat -- forever
display dialog "this is a test, so enter something with \"test\"" default answer "test"
set theAnswer to text returned of the result
if theAnswer contains "test" then exit repeat -- success
end repeat
log theAnswer
Note that although a dialog's cancel button generates a "user cancelled" error, in a stay open script the script won't quit on the error, so you will need to do your own error handling.

How to tell an Applescript to stop executing

Applescript's "choose from list" user interaction has a "cancel" button — I want this "cancel" to tell the script to immediately stop executing. In other words:
set wmColor to choose from list {"Black", "Black for all", "White",
"White for all"} with prompt "What color should the watermark be?"
default items "White for all" without multiple selections allowed and
empty selection allowed
if wmColor is false
*tell script to stop executing*
end if
Can't seem to find how to do this — does anyone know how?
Error number -128 is "User Cancelled", and will stop the script - for example:
if wmColor is false then
error number -128
end if
"return" tells a script to stop executing:
display dialog "Do you want to exit this script?" with icon note buttons {"Exit", "Continue"}
if the button returned of the result is "Exit" then
return
end if
For the specific case of an AppleScript invoked via osascript, it can be terminated, returning a status of 0 to the shell, by doing:
tell me to "exit"
Terminate, emitting a message and returning a status of 1, by doing:
tell me to error "{your message}"
The above writes a line like this to standard error:
{scriptname}: execution error: {your message} (-2700)
Here is an example that replaces the cryptic "-2700" and likely does what jefflovejapan is looking for:
tell me to error "Terminated by user" number 0
which writes this to standard error:
{scriptname}: execution error: Terminated by user (0)
and returns a status of 1.
I learned this by experiment, after reading:
AppleScript Language Guide - error Statements
I found this works well for scripts running within an application (for example, InDesign CS5.5):
repeat 100 times
tell application ("System Events") to keystroke "." using command down
delay (random number from 0.5 to 5)
end repeat
This was modified from this answer.
You can use the word "quit" to quit the current application. You can use this if you save your script as an application.
if wmColor is false
quit
end if

Resources