How do I inject JavaScript and receive messages in Swift?

In this example, we will demonstrate how to inject JavaScript into a WebView in Swift and receive messages back from the JavaScript side.

JavaScript, Swift, WebView, message passing, iOS development
This example illustrates the process of injecting JavaScript into a Swift WebView and handling messages sent from JavaScript.
import UIKit import WebKit class ViewController: UIViewController, WKScriptMessageHandler { var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() let contentController = WKUserContentController() contentController.add(self, name: "callbackHandler") let config = WKWebViewConfiguration() config.userContentController = contentController webView = WKWebView(frame: self.view.frame, configuration: config) self.view.addSubview(webView) let htmlString = """ """ webView.loadHTMLString(htmlString, baseURL: nil) } func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { if message.name == "callbackHandler" { print("Received message from JavaScript: \(message.body)") } } }

JavaScript Swift WebView message passing iOS development