Can I run JavaScript inside Swift code?
Using JavaScriptCore framework include JavaScript code in Swift code.
The class that you’ll be dealing the most with, is JSContext. This class is the actual environment (context) that executes your JavaScript code.
All values in JSContext, are JSValue objects, as the JSValue class represents the datatype of any JavaScript value. That means that if you access a JavaScript variable and a JavaScript function from Swift, both are considered to be JSValue objects.
I strongly advise you to read the official documentation regarding the JavaScriptCore framework.
import JavaScriptCore
var jsContext = JSContext()
// Specify the path to the jssource.js file.
if let jsSourcePath = Bundle.main.path(forResource: "jssource", ofType: "js") {
do {
// Load its contents to a String variable.
let jsSourceContents = try String(contentsOfFile: jsSourcePath)
// Add the Javascript code that currently exists in the jsSourceContents to the Javascript Runtime through the jsContext object.
self.jsContext.evaluateScript(jsSourceContents)
}
catch {
print(error.localizedDescription)
}
}
more details refer this tutorial
Last tested with Swift 5.1
Here is an example you can run in Playground to get you started:
import JavaScriptCore
let jsSource = "var testFunct = function(message) { return \"Test Message: \" + message;}"
var context = JSContext()
context?.evaluateScript(jsSource)
let testFunction = context?.objectForKeyedSubscript("testFunct")
let result = testFunction?.call(withArguments: ["the message"])
result
would be Test Message: the message
.
You also can run JavaScript code within a WKWebView calling evaluateJavaScript(_:completionHandler:).
You can also run JavaScript within a UIWebView by calling stringByEvaluatingJavaScript(from:), but note that that method has been deprecated and is marked as iOS 2.0–12.0.