3

我正在尝试利用 OS X (10.11) 中的新JavaScript 自动化功能来编写不提供字典的应用程序的脚本。我有一个使用原始 Apple 事件与该应用程序交互的 AppleScript,如下所示:

tell application "Bookends"
  return «event ToySSQLS» "authors REGEX 'Johnson' "
end tell

现在我的问题是:如何将其翻译成 JavaScript?我找不到有关 Javascript OSA API 发送和接收原始 Apple 事件的任何信息。

一种可能的解决方法可能是通过 shell 调用一段 AppleScript,但我更喜欢使用“真正的”API。

4

1 回答 1

1

通过在几个辅助函数中使用 OSAKit,您至少可以做一些比 shell 脚本调用更快的事情:

// evalOSA :: String -> String -> IO String
function evalOSA(strLang, strCode) {

    var oScript = ($.OSAScript || (
            ObjC.import('OSAKit'),
            $.OSAScript))
        .alloc.initWithSourceLanguage(
            strCode, $.OSALanguage.languageForName(strLang)
        ),
        error = $(),
        blnCompiled = oScript.compileAndReturnError(error),
        oDesc = blnCompiled ? (
            oScript.executeAndReturnError(error)
        ) : undefined;

    return oDesc ? (
        oDesc.stringValue.js
    ) : error.js.NSLocalizedDescription.js;
}

// eventCode :: String -> String
function eventCode(strCode) {
    return 'tell application "Bookends" to «event ToyS' +
        strCode + '»';
}

然后允许您编写如下函数:

// sqlMatchIDs :: String -> [String]
function sqlMatchIDs(strClause) {
    // SELECT clause without the leading SELECT keyword
    var strResult = evalOSA(
        '', eventCode('SQLS') +
        ' "' + strClause + '"'
    );

    return strResult.indexOf('\r') !== -1 ? (
        strResult.split('\r')
    ) : (strResult ? [strResult] : []);
}

并打电话给

sqlMatchIDs("authors like '%Harrington%'")

更完整的示例集:Bookends 函数的 JavaScript 包装器

于 2016-07-02T21:30:40.830 回答