User Tools

Site Tools


action:Execute_a_JavaScript_For_Automation

**This is an old revision of the document!**

The Execute a JavaScript For Automation action executes a specified JavaScript, either from a file or text.

The results of the script can be:

  • Ignored.
  • Displayed in a floating window.
  • Displayed briefly in a Notification.
  • Typed in to the current selection.
  • Pasted in to the current selection.
  • Saved to a variable.
  • Saved to the system or a Named Clipboard.
  • Asynchronously ignored — the action runs while the macro continues on.

JavaScript For Automation scripts are executed in the background via osascript. This means they are not allowed to do user interaction. You can work around this by asking an application like System Events to do the user interaction for you.

You can access Keyboard Maestro variables by using environment variables or by using the Keyboard Maestro Engine application (7.1+).

Example JXA Script

Shows how to Get/Set Keyboard Maestro Variables, and Get/Set the System Clipboard.

snippet.javascript
'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()
)();

For more information, see:

action/Execute_a_JavaScript_For_Automation.1491424927.txt.gz · Last modified: 2017/04/05 16:42 by JMichaelTX