JMichaelTX
5/4/2015 - 5:23 PM

Yosemite JXA Javascript Function for clicking application sub-menu items

Yosemite JXA Javascript Function for clicking application sub-menu items

// Click an OS X app sub-menu item
// 2nd argument is an array of arbitrary length (exact menu item labels, giving full path)

// e.g. menuItemClick("InqScribe", ['View', 'Aspect Ratio', 'Use Media Ratio'])

// Note that the menu path (spelling & sequence) must be exactly as in the app
// See menuItemTestClick() below for a slower version which reports any errors

// For macOS Yosemite to Sierra

(function () {
    'use strict';

    // menuItemClick :: String -> [String] -> IO Bool
    var menuItemClick = function (strAppName, lstMenuPath) {
        var intMenuPath = lstMenuPath.length;

        if (intMenuPath > 1) {
            var appProcs = Application('System Events')
                .processes.where({
                    name: strAppName
                }),
                procApp = appProcs.length ? appProcs[0] : undefined;

            if (procApp) {
                Application(strAppName)
                    .activate();

                lstMenuPath.slice(1, -1)
                    .reduce(function (a, x) {
                        return a.menuItems[x].menus[x];
                    }, procApp.menuBars[0].menus.byName(lstMenuPath[0]))
                    .menuItems[lstMenuPath[intMenuPath - 1]].click();

                return true;
            }
            return false;
        }
        return false;
    };

    // e.g.
    //menuItemClick('InqScribe', ['Transcript', 'Transcript Settings...']);
    menuItemClick("InqScribe", ['View', 'Aspect Ratio', 'Use Media Ratio'])
})();