Android WebView with JavaScript Interface
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 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.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
Please Login to comment...