Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run JavaScript/AppleScript from cocoa app?

I am trying to execute some AppleScript from Objective-C using NSAppleScript... however, the code I am trying is the new JavaScript for automation in Yosemite. It does not appear to do anything when it is run, however, normal AppleScript works fine.

[NSApp activateIgnoringOtherApps:YES];
NSAppleScript *scriptObject = [[NSAppleScript alloc] initWithSource:
                               @"\n\
                                    iCal = Application(\"Calendar\");\n\
                                    iCal.includeStandardAdditions = true;\n\
                                    iCal.activate();\n\
                                    iCal.displayAlert(\"testing\");\n\
                               "];

[scriptObject executeAndReturnError: nil];

How can I get this to run?

Thanks

like image 432
Brian Peters Avatar asked Feb 12 '23 14:02

Brian Peters


1 Answers

NSAppleScript is hardwired to compile source code as AppleScript. You'd need to use OSAKit instead, which is shoddy and undocumented, but at least allows you to specify which language to use when compiling from source. Alternatively, you could kludge a workaround by piping your source to osacompile -l JavaScript, then loading the resulting compiled .scpt file into NSAppleScript.

However, it's not clear from your example why you're using NSAppleScript. If you want to execute user-supplied scripts you should probably look at NSUserAppleScriptTask: it's even crappier than NSAppleScript, but it's designed to run the script in a subprocess outside your app's sandbox. (NSAppleScript runs scripts in-process, which in a sandboxed app prevents user scripts talking to arbitrary applications.)

OTOH, if you're only using NSAppleScript to run your own code, you'd be much better using Scripting Bridge (which is crappy and broken, but may be sufficient if your needs are modest), or use AppleScript via the AppleScript-ObjC bridge, which allows your ObjC code to use AppleScript-based 'classes' much as if they were native Cocoa classes. Given that AppleScript is the only supported solution that knows how to speak Apple event correctly (JXA's riddled with flaws too), I'd recommend the latter.

like image 194
foo Avatar answered Feb 16 '23 04:02

foo