Click here to Skip to main content
11,796,394 members (71,939 online)
Click here to Skip to main content

Tagged as

Android addJavaScriptInterface

, 11 Dec 2012 CPOL 53.2K 1.8K 13
Rate this:
Please Sign up or sign in to vote.
How to call activity method in your JavaScript code using the addJavascriptInterface method.


Hi everyone again. Today I am going to share my experience with the addJavaScriptInterface method in Android. This class basically helps us call any activity method inside your JavaSscript function. Some of the points I want to mention below: 

  • addJavaScriptInterface method helps us pass values from a webpage to your android XML view or vice-versa. 
  • You can invoke your activity class method form your webpage and vice-versa. 
  • It can be a very useful feature, or a dangerous security issue when the HTML in the WebView is untrustworthy because an attacker could inject HTML that will execute your code and possibly any code of the attacker's choosing.   
  • Do not use addJavascriptInterface() unless all of the HTML in a WebView was written by you. 

This article covers the following points: 

  1. Implementation of JavaScriptInterface and the methods.
  2. Using this interface, I am going to bind a textview control.
  3. Source code of my demo app.


Click here to know more about Webview and the addJavascriptInterface method.

Using the Code

I am going to use an eclipse IDE and I suppose that you have some experience in Android development using the Eclipse IDE. I am going to create a new project named JavaScriptInterfaceDemo. After creating it I am going to add user permission for internet in my AndroidManifest.xml file. 

<uses-permission android:name="android.permission.INTERNET"/>

Then I created a folder named www within my asset folder. After that I created a file index.html within the www folder. I have used webview and textview controls in my layout file named main.xml. My main.xml code is given below.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >
        android:layout_weight="1" />
        android:textAppearance="?android:attr/textAppearanceLarge" />

In the main.xml file, I have used a parent layout. It's a linear layout and within this layout I have used some child controls and layout which are known as webview, textview controls and linear layout.

Now I am going to write a few more lines in my class. Let me show my code.

package my.demo;
import my.demo.R;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Toast;

public class JavaScriptInterfaceDemoActivity extends Activity {
	private WebView Wv;
	private TextView myTextView;	
	final Handler myHandler = new Handler();
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        Wv = (WebView)findViewById(;
        myTextView = (TextView)findViewById(;        
        final JavaScriptInterface myJavaScriptInterface
     	= new JavaScriptInterface(this);    	 
        Wv.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
    public class JavaScriptInterface {
		Context mContext;

	    JavaScriptInterface(Context c) {
	        mContext = c;
	    public void showToast(String webMessage){	    	
	    	final String msgeToast = webMessage;	    Runnable() {
	             public void run() {
	                 // This gets executed on the UI thread so it can safely modify Views

	       Toast.makeText(mContext, webMessage, Toast.LENGTH_SHORT).show();

In my Java class file, I have written some code in the oncreate method. In this method, I find my webview and textview controls using the findViewById method. Then I create a JavaScriptInterface class. This class has a constructor and that constructor initializes the Context class. Now suddenly a question raises in your mind, what is a Context Class?

Context Class is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

After the initialization of the constructor, I create a method named showToast with a string parameter. This method has a variable msgeToast string and then I created a Handler named myHandler. Click here to know more about Handlers. This handler has a Post method. In the method declaration, I create a new instance of the Runnable thread class and inside this class I override a run method. This run method sets the value for the textview control.

Now I create an instance of my JavaScriptInterface class in my OnCreate method. 

final JavaScriptInterface myJavaScriptInterface = new JavaScriptInterface(this);

After the initialization of the JavaScriptInterface class, I added one more line in my OnCreate method:

Wv.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");

Webview provides the addJavascriptInterface method. This method contains two parameters:

  1. The class instance to bind to JavaScript.
  2. The name to be used to expose the instance in JavaScript.

For webview, we need to call some settings to enable the JavaScript.


And finally, you need to provide a web URL in your web view:


Then I created an HTML file named index.html. This HTML file has a textbox and a Submit button. The HTML file code is given below:

<html xmlns="" debug="true">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="viewport" 
          content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="viewport" content="target-densitydpi=device-dpi" />
        <script type="text/javascript">
           function init()
        	   var testVal = document.getElementById('mytextId').value;
        <div style="float: left;width: 50%;">
           <input type="text" style="width: 180px;" 
                   name="myText" id="mytextId" />
        <div style="clear: both;height: 3px;"> </div>
          <input value="submit" type="button" name="submit" 
            id="btnSubmit" onclick="javascript:return init();" /> 

This HTML file has a JavaScript function named init. This function calls the activity method.


AndroidFunction is the same name used to expose the instance in JavaScript. We have already given this name in our addJavascriptInterface method. 

Now finally run your app.

I have also added a toast message in my view.

Points of Interest 

This is a very good feature provided by a addJavascriptInterface method. But you must be more careful when you implement this approach. Otherwise the hacker can inject bad HTML inside code. This is the good thing that I have learned during my development phase. I hope you guys will enjoy it and it will help you out in your problems.  


For more details on the source code, please download the source code from the link at the top of this article. The source code is easy and well commented.

Hope this tutorial is useful.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Sushil Sh.
Software Developer (Senior) Fiserv
India India
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionBecause not work on Android 4.2 or higher Pin
Никита Громик21-Aug-15 2:31
memberНикита Громик21-Aug-15 2:31 
QuestionNot working on S4 android 4.3 Pin
Innovation Lab23-Jan-14 22:53
memberInnovation Lab23-Jan-14 22:53 
AnswerRe: Not working on S4 android 4.3 Pin
Sushil Sh.25-Apr-14 22:22
professionalSushil Sh.25-Apr-14 22:22 
AnswerRe: Not working on S4 android 4.3 Pin
swatig20sg29-Jul-14 1:39
memberswatig20sg29-Jul-14 1:39 
QuestionCan I use this to double click? Pin
Member 95894978-Dec-12 13:34
memberMember 95894978-Dec-12 13:34 
AnswerRe: Can I use this to double click? Pin
Sushil Sh.11-Dec-12 18:26
memberSushil Sh.11-Dec-12 18:26 
AnswerRe: Can I use this to double click? Pin
Sushil Sh.13-Dec-12 0:03
memberSushil Sh.13-Dec-12 0:03 
GeneralRe: Can I use this to double click? Pin
Mark-In-Md13-Dec-12 3:15
memberMark-In-Md13-Dec-12 3:15 
GeneralRe: Can I use this to double click? Pin
zlogic26-Mar-14 1:52
memberzlogic26-Mar-14 1:52 
GeneralRe: Can I use this to double click? Pin
Mark-In-Md26-Mar-14 17:09
memberMark-In-Md26-Mar-14 17:09 
QuestionSome javascript binding history Pin
Lorenzo H. Martín14-Jun-12 21:12
memberLorenzo H. Martín14-Jun-12 21:12 
AnswerRe: Some javascript binding history Pin
Sushil Sh.18-Jun-12 19:45
memberSushil Sh.18-Jun-12 19:45 
GeneralMy vote of 5 Pin
Anil Sh12-Jun-12 20:54
memberAnil Sh12-Jun-12 20:54 
GeneralMy vote of 5 Pin
akhi0gupta00712-Jun-12 19:38
memberakhi0gupta00712-Jun-12 19:38 
GeneralMy vote of 2 Pin
Selvin12-Jun-12 3:18
memberSelvin12-Jun-12 3:18 
GeneralRe: My vote of 2 Pin
Sushil Sh.12-Jun-12 7:20
memberSushil Sh.12-Jun-12 7:20 
Thanks for your vote Selvin.But the thing is that set the textview control text.I struggled lot,Then I found this solution using a handler n all stuff.For toast implementation was easy.But the rest things are not easy to implement at-least for me.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.151002.1 | Last Updated 11 Dec 2012
Article Copyright 2012 by Sushil Sh.
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid