The Execute a JavaScript For Automation action executes the specified script, either from a file or text.
The results of the script can be:
Example JXA Script shows how to Get/Set Keyboard Maestro Variables, and Get/Set the System Clipboard.
'use strict'; (function run() { // this will auto-run when script is executed // --- SET CURRENT APP VARIABLE NEEDED FOR DIALOGS & StandardAdditions.osax --- var app = Application.currentApplication() app.includeStandardAdditions = true // --- SET KME APP VARIABLE NEEDED TO GET/SET KM VARIABLES --- var kme = Application("Keyboard Maestro Engine"); //--- GET A KM VARIABLE --- // Returns empty string if it doesn't exist var someVarNameStr = kme.getvariable("KMVarNameToGet") || 'Default Value if NOT Found'; console.log("someVarNameStr: " + someVarNameStr) var someNewDataStr = "Text to be set to a KM var"; //--- SET A KM VARIABLE --- // Creates the Variable if it doesn't exist // Verify Variable in the KM App Preferences kme.setvariable("KMVarNameToSet", { to: someNewDataStr }); //--- GET TEXT ON CLIPBOARD --- var clipboardStr = app.theClipboard() console.log("clipboardStr: " + clipboardStr) var someDataStr = "Example text to put on clipboard" //--- COPY TO CLIPBOARD --- // Verify using KM Clipboard History Viewer app.setTheClipboardTo(someDataStr) } // END of function run() )();
JavaScript For Automation scripts are executed in the background via osascript. In order to have user interaction in the script, you will need to use a reference to the “current application”. For example:
'use strict'; (function run() { // this will auto-run when script is executed // --- SET CURRENT APP VARIABLE NEEDED FOR DIALOGS & StandardAdditions.osax --- var app = Application.currentApplication() app.includeStandardAdditions = true var MsgStr = "This is an example of JXA Display Dialog" var TitleStr = "Dialog Title" var AnswerStr = "NONE" app.beep() var oAns = app.displayDialog(MsgStr, { withTitle: TitleStr ,withIcon: "caution" ,buttons: ["Cancel","OK"] ,defaultButton: "OK" ,cancelButton: "Cancel" }) //--- Script is stopped here if user chooses "Cancel" --- var BtnStr = oAns.buttonReturned return ("Btn: " + BtnStr) } // END of function run() )();
For more information, see: