Variable into AppleScript (shell)

Hi, I’m trying to pass a variable via Applescript (Shell) into some text frame in Safari.
The script works and sends a key press “a”, but adding “b” fails (when it is a variable):

dim sh as new shell
var text1 as string =“b”

sh.Execute “osascript -e”_
+“‘tell application ““Safari””’ -e”_
+“‘activate’ -e”_
+“‘tell application ““system events””’ -e”_
+“‘keystroke ““a””’ -e”_
+“‘delay 1’ -e”_
+“‘keystroke text1’ -e”_ '***********
+“‘end tell’ -e”_
+“‘end tell’”

I fiddled with quotation marks, brackets etc but without any success using the variable:

101,106: execution error: the variable is not defined (-2753)”

“not defined” what does it mean and how do I define it?

A few things:

  • Your code snippet appears to include smart quotes (the fancy version of regular " marks so will not work as you posted it).
  • please remember to use the Preformatted Text toolbar for code snippets in the forum
  • the quoting is messed up for the text1 variable
  • I like to use the Bash HEREDOC format which solves some of the quoting issues and makes the script easier to read and debug
  • you can set a breakpoint in the debugger and copy the cmd variable and paste it into a Text editor, and/or to the Terminal window to debug it.

This code works:

dim CR as string = EndOfLine.UNIX
var text1 as string = "b"

dim cmd as string = _
"osascript << ""EOF""" + CR +_
"tell application ""Safari"" " + CR +_
"  activate" + CR +_
"  tell application ""system events"" " + CR +_
"    keystroke ""a"" " + CR +_
"    delay 1" + CR +_
"    keystroke """ + text1  + """ " + CR +_
"  end tell" + CR +_
"end tell" + CR + _

dim sh as new shell
sh.Execute cmd
1 Like

The hair-tearing quotatation being a mess, is a great understatement! :slight_smile: I modified old code that I used 15 years ago (remembering the quotation mess back then.).

Your example seems to do the job (with a much more readable code).
Thank you!