javascript in AppleScript

Good evening everyone. I can't run a line of JavaScript in AppleScript. Is that normal? It's normal? Thank you in advance.

I can't run a line of JavaScript in AppleScript.

AppleScript can’t run JavaScript by itself. If you want to run JavaScript, you have to do it in a context that understands JavaScript. For example, this AppleScript code:

tell application "Safari"
    set t to tab 1 of window 1
    do JavaScript "1+1" in t
end tell

runs a JavaScript in the first tab of the frontmost window of Safari.

IMPORTANT For this to work you must enable it via Safari > Develop > Allow JavaScript from Apple Events. If you don’t have the Develop menu in Safari, enable that in Safari > Preferences > Advanced.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

You can execute JavaScript in AppleScript by using WebKit or JavaScriptCore.


use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "JavaScriptCore"
use framework "WebKit"

--JavaScript Text
set jsText to "let bar = 2;
bar += 2;
"

--Execute JavaScript in WebKit
set theWebView to current application's WebView's alloc()'s init()
set x to (theWebView's stringByEvaluatingJavaScriptFromString:jsText) as text
log {x, "2"}

--Execute JavaScript in JavaScript Core
set theContext to current application's JSContext's alloc()'s init()
set theJSValue to theContext's evaluateScript:jsText
log {theJSValue, "3"}

You have to execute this AppleScript on Script Editor by Control-Command-R(Run in Main thread).

javascript in AppleScript
 
 
Q