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 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.
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')")
}
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
Syntaxerror: Unexpected Token Function - Async Await Nodejs
In iOS8 Using .Focus() Will Show Virtual Keyboard and Scroll Page After Touch
Why Is the Ecc-Dh Symmetric Key of This Site Different from Openssl
How to Geocode 20 Addresses Without Receiving an Over_Query_Limit Response
Rendering React Components with Promises Inside the Render Method
JavaScript Dom Changes in Touchmove Delayed Until Scroll Ends on Mobile Safari
Splitting a Js Array into N Arrays
How to Use Ranges in a Switch Case Statement Using JavaScript
How Does JavaScript Determine the Number of Digits to Produce When Formatting Floating-Point Values
Wkwebkit JavaScript Execution When Not Attached to a View Hierarchy
Using Enter Key with Action Button in R Shiny
Slow Assets Compilation in Development Mode
Uint8Array to String in JavaScript
Creating a "Sticky" Fixed-Position Item That Works on iOS Safari
What's the Best Way to Calculate Date Difference in JavaScript