Invoking Java/Kotlin code from JavaScript
If you need to trigger Java or Kotlin code from your JavaScript, Android WebView offers a solution known as Javascript Interface.
This feature enables the execution of java/kotlin functions from within your javascript code.
To accomplish this, you can create an interface like so:
val webView: WebView = findViewById(R.id.webview)
webView.addJavascriptInterface(WebAppInterface(this), "Android")
In this snippet, WebAppInterface defines the methods that can be invoked from javascript.
/** Create an instance of the interface and provide the context */
class WebAppInterface(private val mContext: Context) {
/** Display a toast on the web page */
@JavascriptInterface
fun showToast(toast: String) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show()
}
}
The name "Android" serves as the bridge between your webview and javascript, allowing for method calls in the latter.
With this setup, calling these methods from your javascript becomes possible:
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
Note that callbacks from the interface do not always occur in the main thread. To execute UI-related tasks, remember to utilize runOnUiThread.
Triggering JavaScript function from Java/Kotlin code
For scenarios where you need to call javascript functions from your Java or Kotlin code in Android WebView, you can leverage the Evaluate Javascript feature introduced in API level 19.
Here's an example with the following javascript method:
<script type="text/javascript">
function printName(name) {
console.log(name);
}
</script>
You can invoke this JavaScript function using the following code:
yourWebview.evaluateJavascript("printName(\'TEST\')")