JavaScript has various standard libraries which AppleScript lacks (URL encode-decode, and trigonometic functions come to mind for example).
A common AppleScript solution is to use do shell script
to get these kinds of missing functionality, and shelling out could even include a call to "osascript -l JavaScript -e strCode"
Here, however, is an AppleScript function
evalOSA()
which allows you to evaluate JavaScript code (from an AppleScript) a little more directly.
( A JavaScript version of evalOSA() (for evaluating AS or JS) follows further below )
Turns out be significantly faster than calling to osascript through the shell, both from AS and from JS.
Examples: call JS from AS and vice versa.kmmacros (21.2 KB)
AppleScript source:
use framework "OSAKit"
on run
set strEncoded to ¬
evalOSA("JavaScript", "encodeURIComponent('Read Me First.txt')")
end run
-- evalOSA :: ("JavaScript" | "AppleScript") -> String -> String
on evalOSA(strLang, strCode)
set ca to current application
set oScript to ca's OSAScript's alloc's initWithSource:strCode ¬
|language|:(ca's OSALanguage's languageForName:(strLang))
set {blnCompiled, oError} to oScript's compileAndReturnError:(reference)
if blnCompiled then
set {oDesc, oError} to oScript's executeAndReturnError:(reference)
if (oError is missing value) then return oDesc's stringValue as text
end if
return oError's NSLocalizedDescription as text
end evalOSA
JavaScript Source:
function run() {
ObjC.import('OSAKit');
return ['JS', 'AS']
.map(function (strLang) {
return evalOSA(strLang, '2 + 2');
});
}
function evalOSA(strLang, strCode) {
var strIdiom = strLang.toLowerCase()
.indexOf('j') !== -1 ? (
'JavaScript'
) : 'AppleScript',
error = $(),
oScript = (
$.OSALanguage.setDefaultLanguage(
$.OSALanguage.languageForName(strIdiom)
),
$.OSAScript.alloc.initWithSource(strCode)
),
blnCompiled = oScript.compileAndReturnError(error),
oDesc = blnCompiled ? (
oScript.executeAndReturnError(error)
) : undefined;
return oDesc ? (
oDesc.stringValue.js
) : error.js.NSLocalizedDescription.js;
}