Issue
I'm using android webview and want to make dynamic function calls over the Javascript Interface. My interface's name is AndroidBridge. And here is my code:
AndroidBridge[key](values[key]);
It works properly on the browser. But when it comes to my webview, is throwing the error below:
Error connecting controller TypeError: AndroidBridge[key] is not a function [object Object]"
Any advice to jump over that issue?
Solution
I can give you the two possible reasons for that issue now:
- Missing
@JavascriptInterface
annotation. - The method is missing or params not matching.
I don't know why browser's js interpreter looks to "a square named version of that object", but method names that match should work without that errors.
I can leave here a fully working example:
class JsBridge {
@JavascriptInterface
fun showToast(message: String) {
Log.d("DEBUG", "JsBridge showToast message:$message")
val currentActivity = current ?: return
Toast.makeText(currentActivity, message, Toast.LENGTH_SHORT).show()
}
companion object {
@JvmStatic
val instance: JsBridge = JsBridge()
}
}
// Somewhere in your code
webView.addJavascriptInterface(JsBridge.instance, "AndroidBridge")
Now you can call that method in the js side:
AndroidBridge.showToast('A message');
// or
AndroidBridge['showToast']('A message');
They both should work.
Answered By - Yunus Emre
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.