【问题标题】:Sending and receiving "raw" Apple Events from JavaScript on OS X (El Capitan)在 OS X (El Capitan) 上从 JavaScript 发送和接收“原始”Apple 事件
【发布时间】:2016-04-19 20:28:06
【问题描述】:

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

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

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

一种可能的解决方法是call a piece of AppleScript through the shell,但我更愿意使用“真正的”API。

【问题讨论】:

    标签: javascript applescript osx-elcapitan javascript-automation


    【解决方案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%'")
    

    这里有更完整的示例:JavaScript wrappers for Bookends functions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-30
      • 1970-01-01
      • 1970-01-01
      • 2015-12-29
      • 1970-01-01
      • 2017-06-11
      • 2016-01-03
      • 1970-01-01
      相关资源
      最近更新 更多