3

我想在OS X(10.11)中使用新的JavaScript Automation feature來編寫不提供字典的應用程序。我有一個AppleScript,使用原始Apple事件與該應用程序交互,如下所示:從OS X(El Capitan)上的JavaScript發送和接收「原始」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。

回答

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

相關問題