JavaScript Interface for Android Webview

Updated 31 January 2024

Save

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

index.html

Output:

Calling Java/Kotlin Method from JavaScript

Calling JS Function from Java/Kotlin

Output:

Calling JS Function from Java/Kotlin

MainActivity’s code

main_activity

activity_main.xml

activity_main

Conclusion

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

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home