The issue I'm facing is that the JavaScript message is not being sent to Swift as expected.
Here's the Swift Code:
class FirstViewController: UIViewController, WKUIDelegate, WKScriptMessageHandler {
@IBOutlet weak var webview: WKWebView!
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print( "Enter here" )
if message.name == "jsHandler" {
print( message.body );
}
}
override func viewDidLoad() {
super.viewDidLoad()
let htmlPath = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "web")
let url = URL(fileURLWithPath: htmlPath!)
let request = URLRequest(url: url)
let user = WKUserContentController()
user.add(self, name: "jsHandler")
webview.configuration.userContentController = user
webview.uiDelegate = self
webview.navigationDelegate = self
webview.load(request)
}
And here's the JavaScript code:
$(document).on( 'click', '.element', function() {
window.webkit.messageHandlers.jsHandler.postMessage( "Invoke swift" );
} );
I'm wondering if there might be something wrong with this setup or if I'm missing a crucial step. Any help would be greatly appreciated!