如何在macOS上从JXA/JavaScript for Automation脚本运行内联Applescript? [英] How do you run inline Applescript from a JXA/JavaScript for Automation script on macOS?

查看:180
本文介绍了如何在macOS上从JXA/JavaScript for Automation脚本运行内联Applescript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用JavaScript编写的脚本,该脚本需要运行一小段AppleScript(要实现某些功能,由于JS中固有的多种因素,我无法实现这些功能).

I have a script written in JavaScript which needs to run one small piece of AppleScript (to achieve some functionality I've been unable to implement due to a number of factors natively in JS).

它应该能够接受单个字符串参数,并且几乎可以说是一句话.

It should be able to take a single string argument, and is pretty much a tell-endtell one liner.

是否有可能在JavaScript中将该纳米程序组装为字符串,然后将该字符串传递给AppleScript环境以执行该代码?

Is it possible to assemble this nanoprogramme as a string in JavaScript then pass the string to the AppleScript environment for execution, and how would that be done?

在线上有很多关于如何从Applescript运行JavaScript的解释,但反之则不多.

There's plenty of explanations online about how to run JavaScript from Applescript, but not as much coming the other way.

这很可能会涉及到osascript -e的shell调用来实现,还是有更清洁的JXA-ey方法?

Would this - in all likelihood - involve a shell invocation of osascript -e to achieve, or are there cleaner, more JXA-ey ways?

推荐答案

这是ES6(从Sierra开始)macOS的evalAS函数.

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');

})();

shell方法的优点在于,可以在评估环境中自动添加脚本.

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

如果我们使用以下evalSA的替代定义,则需要在表达式字符串前显式地添加使用脚本附加项\ n"

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'
    );
})();

这篇关于如何在macOS上从JXA/JavaScript for Automation脚本运行内联Applescript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆