How to return data from WKWebView in JavaScript

I am developing a hybrid application for Android and iOS using WebView. However, I am trying to return data from an iOS application back to my Javascript.

The following describes how I configure WebView to retrieve data from my JavaScript functions.

private lazy var webViewConfiguration: WKWebViewConfiguration = {
    let configuration = WKWebViewConfiguration()
    configuration.userContentController.add(self, name: "loginController")
    return configuration
}()


extension ApplicationController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    if (message.name == "loginController"){
        print("\(message.body)")
    }
}
}

This is how I pass data to the application.

webkit.messageHandlers.loginController.postMessage("Hello from JavaScript");

Essentially, I would like to get the data back from the application into my JavaScript and do something like that ...

var response = webkit.messageHandlers.loginController.postMessage("Hello from JavaScript");

But I can’t figure out how to return something from the application. I am new to Swift. However, for Android dev, this may be as simple as adding a return type to my function, but this does not work for Swift.

+4
source share

Source: https://habr.com/ru/post/1680876/


All Articles