How do you run inline Applescript from a JXA/JavaScript for Automation script on macOS?

泄露秘密 提交于 2019-12-01 01:45:03

Here is an evalAS function for ES6 (Sierra onwards) macOS.

(() => {
    'use strict';

    // evalAS :: String -> IO String
    const evalAS = s => {
        const
            a = Application.currentApplication(),
            sa = (a.includeStandardAdditions = true, a);
        return sa.doShellScript(
            ['osascript -l AppleScript <<OSA_END 2>/dev/null']
            .concat([s])
            .concat('OSA_END')
            .join('\n')
        );
    };

    return evalAS('tell application \"Finder\" to the clipboard');

})();

The advantage of the shell approach is simply that scripting additions are automatically available in the evaluation environment.

If we use the following alternative definition of evalSA, we need to explicitly prepend our expression string with 'use scripting additions\n'

(() => {
    'use strict';

    // evalAS2 :: String -> IO a
    const evalAS2 = s => {
        const a = Application.currentApplication();
        return (a.includeStandardAdditions = true, a)
            .runScript(s);
    };

    return evalAS2(
        'use scripting additions\n\
        tell Application "Finder" to the clipboard'
    );
})();

Use Standard Additions' run script command.

(BTW, my standard recommendation is to stick to using AppleScript for application automation as it's the only [supported] option that works right. JXA's various bugs, defects, and omissions were known about before even it shipped, and Apple couldn't be bothered to fix them back then, so they certainly won't be fixed now the Automation team has been eliminated. The whole Mac Automation platform's dying anyway, but at least AppleScript should bitrot slower than JXA, which was never right to begin with.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!