I have been doing some simple JavaScript examples and not only in Safari.
This ones use JavaScriptCore Framework.
We could also send AS arguments to the JavaScript code, execute it… and return AS value.
Nice way to run simple JavaScript functions.
use framework "Foundation"
use framework "JavaScriptCore"
use scripting additions
set theString to "heLLo world!"
set {theNumber, idx} to {"9.656", 2}
(**
* JS function upperCase(str)
*)
set upperCaseJS to "function upperCase(str) {
//
return str.toUpperCase()
}
//
upperCase('" & theString & "')"
----------
(**
* JS function lowerCase(str)
*)
set lowerCaseJS to "function lowerCase(str) {
//
return str.toLowerCase()
}
//
lowerCase('" & theString & "')"
----------
set titleCaseJS to "function titleCase(str) {
//
return str.replace(/\\b\\w/g, function (txt) {return txt.toUpperCase(); });
}
//
titleCase('" & theString & "')"
----------
set theDegToRadJS to "function degToRad(degrees) {
//
return degrees * (Math.PI / 180);
}
//
50 * (degToRad(60))"
----------
set theToFixedJS to "function toFixedFunc(inputString, idx) {
var x = inputString;
return x.toFixed(idx);
}
//
toFixedFunc(" & theNumber & "," & idx & ")"
----------
set theEncodeURI to "function theFuncURI() {
const uri = 'https://mozilla.org/?x=шеллы';
const encoded = encodeURI(uri);
return encoded;
try {
return (decodeURI(encoded));
} catch (e) {
console.error(e);
}
}
// Run JS Script function
theFuncURI()"
----------
(**
* JavaScriptCore Framework
*)
set theJSContext to current application's JSContext's new()
-- set theEvaluateScript to ((theJSContext's evaluateScript:"Math.PI")'s toObject() as text)
set theEvaluateScript to ((theJSContext's evaluateScript:upperCaseJS)'s toObject() as text)
log its theEvaluateScript
set theJSContext to current application's JSContext's new()
set theEvaluateScript to ((theJSContext's evaluateScript:lowerCaseJS)'s toObject() as text)
log its theEvaluateScript
set theJSContext to current application's JSContext's new()
set theEvaluateScript to ((theJSContext's evaluateScript:titleCaseJS)'s toObject() as text)
log its theEvaluateScript
set theJSContext to current application's JSContext's new()
set theEvaluateScript to ((theJSContext's evaluateScript:theDegToRadJS)'s toObject() as text)
log its theEvaluateScript
set theJSContext to current application's JSContext's new()
set theEvaluateScript to ((theJSContext's evaluateScript:theToFixedJS)'s toObject() as text)
log its theEvaluateScript
set theJSContext to current application's JSContext's new()
set theEvaluateScript to ((theJSContext's evaluateScript:theEncodeURI)'s toObject() as text)
log its theEvaluateScript