Hey Folks,
Someone posted this and then withdrew it.
I tested the code, and it works perfectly on my macOS 10.12.6 Sierra system, so I'm posting it for posterity.
Our own @CJK gets the credit.
-Chris
// --------------------------------------------------------
// @CJK
// 2019.06.02 · 15:49
// Toggle caps lock programmatically using AppleScript's JavaScript for Automation (JXA)
// https://apple.stackexchange.com/questions/361373/toggle-caps-lock-programmatically-using-applescript
// --------------------------------------------------------
ObjC.import("IOKit");
ObjC.import("CoreServices");
(() => {
var ioConnect = Ref();
var state = Ref();
$.IOServiceOpen(
$.IOServiceGetMatchingService(
$.kIOMasterPortDefault,
$.IOServiceMatching(
$.kIOHIDSystemClass
)
),
$.mach_task_self_,
$.kIOHIDParamConnectType,
ioConnect
);
$.IOHIDGetModifierLockState(ioConnect, $.kIOHIDCapsLockState, state);
$.IOHIDSetModifierLockState(ioConnect, $.kIOHIDCapsLockState, !state[0]);
$.IOServiceClose(ioConnect);
})();