How do I run JavaScript / AppleScript from a cocoa app?

I'm trying to execute some AppleScript from Objective-C using NSAppleScript ... however, the code I'm trying to do is new JavaScript to automate in Yosemite. It doesn't seem to do anything when it works, 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 to do it?

thank

+3


source to share


1 answer


NSAppleScript is tightly coupled with compiling source code as AppleScript. You will need to use OSAKit instead, which is cheesy and undocumented, but at least lets you specify which language to use when compiling from source. Alternatively, you can disable the workaround by linking your source to osacompile -l JavaScript

, and then loading the resulting compiled file .scpt

into NSAppleScript.

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



OTOH, if you are using NSAppleScript to run your own code, you would be much better off using the Scripting Bridge (which is crappy and broken, but may suffice if your needs are modest) or use AppleScript over the AppleScript-ObjC bridge that allows your ObjC code to use AppleScript-based "classes" as if they were native Cocoa classes. Given that AppleScript is the only supported solution that knows how to properly talk about Apple events (JXA is riddled with flaws), I would recommend the latter.

+4


source







All Articles