Start a Project

JavaScript Interface for Android Webview

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.

Binding JavaScript to Android

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:

Calling Java/Kotlin Method from JavaScript

Create a JavaScript Interface Class

Note@JavascriptInterface annotation is required for API 17 and above.

Then install this interface using the following code.

Let’s create an HTML file where we will use our Java/Kotlin functions

Output:

Calling JS Function from Java/Kotlin

Output:

MainActivity’s code

activity_main.xml

Conclusion

This is it, hope you have understood how we can use an interface to communicate with our JS code and vice versa.

Exit mobile version