Updated 31 January 2024
In this article, we are going to learn how we can call android functions using javascript and vice versa using the javascript interface for android webview.
To know about webview and how it works, head over here.
For javascript to work in our webview, we need to enable it using webview settings.
1 2 3 4 5 |
Java: webView.getSettings().setJavaScriptEnabled(true); Kotlin: webView.settings.javaScriptEnabled = true |
Through an interface, WebView enables us to connect JavaScript code to Android code.
The class that provides the interface for JS must be passed, along with the name that will be used to show the instance in JS (for example, “Android”).
As a result, an interface called Android will be created for JavaScript that is running in WebView.
By using the interface we can achieve the following:
Create a JavaScript Interface Class
1 2 3 4 5 6 7 8 9 10 11 |
class MyJsInterface(private val mContext: Context) { @JavascriptInterface fun getAndroidVersion(): Int { return Build.VERSION.SDK_INT } @JavascriptInterface fun showToast() { Toast.makeText(mContext, "Toast from android", Toast.LENGTH_SHORT).show() } } |
Note: @JavascriptInterface annotation is required for API 17 and above.
Then install this interface using the following code.
1 2 3 4 5 |
Java: webView.addJavascriptInterface(new MainActivity.MyJsInterface(this), "Android") Kotlin: webview.addJavascriptInterface(MyJsInterface(this), "Android") |
Let’s create an HTML file where we will use our Java/Kotlin functions
Output:
Calling JS Function from Java/Kotlin
1 2 3 4 5 6 7 8 |
findViewById<Button>(R.id.button).apply { setOnClickListener { // Calling JS function from Android // This name should match the name of the method that // you have declared in your JS file webView.loadUrl("javascript:increaseCount()") } } |
Output:
MainActivity’s code
activity_main.xml
This is it, hope you have understood how we can use an interface to communicate with our JS code and vice versa.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.