How to Run JavaScript Inside Swift Code

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.

How to run javascript in a webview from Swift

You need to convert info in javascript alert into native UIAlert.

Add alert handler delegate described in WKUIDelegate.

func webView(_ webView: WKWebView,
runJavaScriptAlertPanelWithMessage message: String,
initiatedByFrame frame: WKFrameInfo,
completionHandler: @escaping () -> Void) {

let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
let title = NSLocalizedString("OK", comment: "OK Button")
let ok = UIAlertAction(title: title, style: .default) { (action: UIAlertAction) -> Void in
alert.dismiss(animated: true, completion: nil)
}
alert.addAction(ok)
present(alert, animated: true)
completionHandler()
}

And call like below (there is a type in your code);

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("alert('hello from the webview')")
}

Sample Image



In Addition

There is a sample project that simulates two way communication between native and web in both way.

is it possible to run swift on a webpage like js or swift to interact with JS

Yes and no. Swift runs in the browser but it cannot access system APIs unless you run it inside a custom-made browser.

Running swift in a browser

It is possible to run Swift code in a browser. You can use SwiftWasm for that. Some practical information can be found in the SwiftWasm book

Swift ⇄ javascript interaction

It is also possible to interact with javascript. See: https://github.com/swiftwasm/JavaScriptKit

System API Access

It is not possible to access system APIs through a normal browser though. If you want access to those APIs, you should create a native app. Note that from within native apps you can also create web content. In such apps you do have access to system APIs through WKUserContentController's add(_:name:) method.

Calling swift Code From Javascript

Yes you can.

Please refer to this Tutorial: https://www.raywenderlich.com/124075/javascriptcore-tutorial

You are interested in the paragraph "Exposing Native Code"

In obj-c is very simple. You can do it just by using your jsContext as a normal dictionary.

context[@"functionName"] = ^ <#returnType#> (<#parameters#>) {
<#Your code#>
}

Hope it helped.

Can Swift Scripts Execute in a Swift iOS App?

As user jvnpdx stated, it is not possible to dynamically run a Swift script within the app.



Related Topics



Leave a reply



Submit