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

查看:18
本文介绍了如何在 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 中将这个 nanoprogramme 组装为一个字符串,然后将该字符串传递给 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 的方法?

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天全站免登陆