'How to return data from WKWebView to JavaScript
I am developing a hybrid Android and iOS app using WebViews. However, I am struggling to return data from iOS app back to my Javascript.
Below is how I setup the WebView to receive 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 app.
webkit.messageHandlers.loginController.postMessage("Hello from JavaScript");
Essentially, what I'd like to do is be able to receive data back from the app to my JavaScript and do something along the lines of this...
var response = webkit.messageHandlers.loginController.postMessage("Hello from JavaScript");
But I cannot figure out how to return something from the app. I'm new to Swift. However for Android dev it can be as simple as adding a return type to my function, but this does not work for Swift.
Solution 1:[1]
Use WebView's evaluateJavaScript function to inject JS code into your window.
webView?.evaluateJavaScript("responseFromLoginController('Hello from Swift')")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Šar?nas Sirotka |