Android WebView with JavaScript Interface
Last Updated :
30 Sep, 2022
JavascriptInterface Annotation provides the facility to create any method as the javascript Interface which means that method can be used by web components to communicate with Android. For example:
- To store the web-based data in Android Shared Preference, or in a local Database.
- To show a customized dialog box.
- Storing the web content in Android Clipboard
- Sharing web content in various applications of Android etc.
So to understand this concept let's create a small project where the user would be entering the basic details and that details would be shown in Android's Dialog box. For this article, we will be using the concept of WebView.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the activity_main.xml file
Navigate to app > res > layout > activity_main.xml and add the below code to it. Comments are added in the code to get to know in detail.
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/interface_web"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Here we have added WebView to our layout file. now we need to load a URL in this WebView, so here we are creating a simple HTML file that would be locally stored in the Assets folder of the Android project.
Step 3: Creating a HTML file
test.html
HTML
<html>
<body bgcolor="red">
<center>
<br/>
<input id="fname" type="text" placeholder="enter your name"/>
<br/>
<br/>
<input id="pswd" type="text" placeholder=" password"/>
<br/>
<br/>
<button onclick="msg();">onclick</button>
</center>
</body>
<script>
function msg(){
var fname=document.getElementById("fname").value;
var pswd=document.getElementById("pswd").value;
// Dialog is javascript interface name
// mentioned in Mainactivity.Java
Dialog.showMsg(fname,pswd);
}
</script>
</html>
Step 4: Working with the MainActivity file
Navigate to app > java > your app's package name > MainActivity file and add the below code to it. Comments are added in the code to get to know in detail. In this Java file, we need to enable JavaScript for the WebView and to add the javascript interface we need to provide the class name as we are adding this in the same file so we are using "webView.addJavascriptInterface(this, "Dialog");"
Java
package com.geeksforgeeks.jsinterface;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.interface_web);
// opening the html file in webview
webView.loadUrl("file:///android_asset/test.html");
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.addJavascriptInterface(this, "Dialog");
}
@JavascriptInterface
public void showMsg(String fname, String pswd) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Confirmation").setMessage("UserName:\t" + fname +
"\nPassword:\t" + pswd)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(), " Data Saved Locally", Toast.LENGTH_SHORT).show();
// You can use shared preference or db here to store The Data
}
})
;
builder.create().show();
}
}
So here when the user clicks on the button of the webpage it will call the showMsg() of Android and from that method dialog box would be shown to the user. here we can save the details in the local database or we can perform various tasks by accessing the web content in android this can be done in a more dynamic way. as per the requirement.
Output:
User Input
Data parsing
Success Message
Similar Reads
Android ListView in Java with Example A ListView in Android is a type of AdapterView that displays a vertically scrollable list of items, with each item positioned one below the other. Using an adapter, items are inserted into the list from an array or database efficiently. For displaying the items in the list method setAdaptor() is use
3 min read
How to Enable JavaScript on Android ? JavaScript is the world's most popular lightweight, interpreted compiled programming language. It is also known as a scripting language for web pages. It is well-known for the development of web pages, many non-browser environments also use it. Therefore nowadays it is essential for users to have Ja
2 min read
TextView in Android with Example TextView is a simple widget that is seen in every android application. This widget is used to display simple text within the android application. We can add custom styling to the text that we have to show. In this article, we will take a look at How to create a simple Text View in an android applica
2 min read
PhotoView in Android with Example In this article, PhotoView is added to android. PhotoView aims to help produce an easily usable implementation of a zooming Android ImageView using multi-touch and double-tap. Besides that, it has many more features like it notifying the application when the user taps on the photo or when the displa
2 min read
PhotoView in Android with Example In this article, PhotoView is added to android. PhotoView aims to help produce an easily usable implementation of a zooming Android ImageView using multi-touch and double-tap. Besides that, it has many more features like it notifying the application when the user taps on the photo or when the displa
2 min read
How to Create Dynamic WebView in Android with Firebase? Converting a website into an application seems like a basic task to do on Android. With the help of WebView, we can show any webpage in our Android Application. We just have to implement the widget of WebView and add the URL inside the WebView which we have to load. So if you are looking for loading
6 min read