Can I run JavaScript inside Swift code?

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 evaluate​Java​Script(_:​completion​Handler:​).

You can also run JavaScript within a UIWebView by calling string​By​Evaluating​Java​Script(from:​), but note that that method has been deprecated and is marked as iOS 2.0–12.0.

Leave a Comment