I tried to execute code in android from the web view through events. So I implemented the good way with a JavascriptInterface, but since I have a iOS Application, I wanted to use the same method. So is this possible to use the message handler on Android (just a simple JS event) rather than the Bridging of the interface ? I also tried to the other way : Make a bridge on iOS the same way of Android, but it doesn't work with WKWebview (but it's another problem) Thanks !
I tried to execute code in android from the web view through events. So I implemented the good way with a JavascriptInterface, but since I have a iOS Application, I wanted to use the same method. So is this possible to use the message handler on Android (just a simple JS event) rather than the Bridging of the interface ? I also tried to the other way : Make a bridge on iOS the same way of Android, but it doesn't work with WKWebview (but it's another problem) Thanks !
Share Improve this question asked Sep 28, 2016 at 10:03 zargholzarghol 4985 silver badges20 bronze badges 3- Have you found a solution for this? – RobVoisey Commented Nov 29, 2016 at 12:52
- I am interested in that too.. Have you found a solution? – K.E. Commented Apr 7, 2018 at 15:45
- 1 Hi, no, I currently use the JavascriptInterface... – zarghol Commented Apr 8, 2018 at 18:31
1 Answer
Reset to default 6This is not remended, if you have the option to change your JS-code and add a conditional handler, you should do that instead.
If you have implemented a handler in iOS using userContentController
and want to reuse it in Android, you can inject JS to replace the window.webkit.messageHandlers
property with your android equivalent.
Say this is your swift code:
webView.configuration.userContentController.add(self, name: "iosListener")
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
//handle message
}
And your JS code:
window.webkit.messageHandlers.iosListener.postMessage("some message")
You can reuse it in android/kotlin without changing your JS code like this:
inner class MyJsInterface() {
@JavascriptInterface
fun postMessage(value: String) {
//handle message
}
}
webView.run {
settings.javaScriptEnabled = true
addJavascriptInterface(MyJsInterface(), "AndroidListener")
webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
evaluateJavascript("window.webkit = { messageHandlers: { iosListener: window.AndroidListener} }") {}
}
}
}