Check Mobile App
Read now
Start a Project

JavaScript Interface for Android Webview

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:

js_calling_java_code

Calling JS Function from Java/Kotlin

Output:

java_calling_js_code

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.

. . .

Leave a Comment

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


Be the first to comment.

css.php

The support is fast and do everything in their power to make it perfect. If you need customization it's also done right away. I had massive research to select Mobikul and now I'm sure it was the right one.

Igor Souza

Igor Souza

Talk to Sales

Global

Live Chat
Start a Project

    Message Sent!

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

    Back to Home