Copy link to clipboard
Copied
I'm running a javascript via Applescript, and I want to return a value back to the calling applescript. When I try the following test:
tell application "Adobe Illustrator"
set theScript to "return 'Test';"
set theResult to do Javascript theScript
end tell
I get a message "'Illegal 'return' outside of a function body".
Is there a way to return a value back to the applescript?
1 Correct answer
there is, look in the Scripting Reference, this is what it says in the VB version, there must be something similar for AS
This example returns the number of open documents.
Set myNumberOfDocuments = appRef.DoJavaScript("documents.length;")
MsgBox myNumberOfDocuments
Explore related tutorials & articles
Copy link to clipboard
Copied
there is, look in the Scripting Reference, this is what it says in the VB version, there must be something similar for AS
This example returns the number of open documents.
Set myNumberOfDocuments = appRef.DoJavaScript("documents.length;")
MsgBox myNumberOfDocuments
Copy link to clipboard
Copied
Thanks, removing the 'return' does do the trick in applescript. Seems so counterintuitive though.
Copy link to clipboard
Copied
Mark, more offen than not your a javascript is going to exit with 'undefined' and that's what you are going to get as the result in AppleScript… In AppleScript you can return a value anywhere… Not so in JavaScript so you have the choice of making a function and calling it to get your values… As my example or you can use the evaluation of the last line as Carlos has shown…
set js to "function test() { return app.activeDocument.name }; test();"
tell application "Adobe Illustrator"
do javascript js
display dialog the result
end tell
Copy link to clipboard
Copied
Thanks.
In my case, I am returning a string with filepaths that are being saved out during the execution of the javascript, and the applescript will pass that string back to another program to load those files into a database. I don't believe I should have a problem with 'undefined' (since I am initializing the variable to an empty string at the start), but I'll make sure that the program can handle that result in case it does happen. Actually, I don't think that should be a problem even if it does occur - since my program validates that it has a valid filepath and the file exists before importing it - and the 'undefined' string would fail to meet those criteria.

