How to make bridge between Android and JavaScript


Now days Web Mobile apps and Hybrid applications are on trends.  This blog is about how we can make a bridge between Web form and android native methods in android apps using JavaScript.

Let's start with add basic code to create bridge.

First of all create Android project in Android Studio. Create an Activity class and layout file.

Now open layout file of activity and add EditText( for typing a message), add button for sending message to webpage and WebView for loading webpage.

Your xml layout look like:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.aman.webviewcallback.MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_margin="10dp"
        android:hint="Type your message" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="87dp"
        android:layout_marginStart="87dp"
        android:onClick="onBtnClick"
        android:text="Send Message To WebView" />


    <TextView
        android:layout_width="match_parent"
        android:layout_marginTop="20dp"
        android:text="WebView Page is loaded below"
        android:layout_height="wrap_content" />
    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/button"
        android:layout_marginTop="10dp" />

</LinearLayout>

Now open java class of Activity and initialize views on onCreate.
  webView = (WebView) findViewById(R.id.webview);
  editText = (EditText) findViewById(R.id.editText);

We have a webView object in Activity class. Now we have to setJavascriptEnable true by calling method webView.getSettings().setJavaScriptEnabled(true) for enable execution of javascript in webview which is false by default.
webView.getSettings().setJavaScriptEnabled(true);

With enabling javascript to webview now we will add JavaScriptInterface to webview which will help to create bridge between JavaScript and Java code. It takes 2 parameters . Instance of class which will be injected from Javascript and name which will help to invoke method of java class.
webView.addJavascriptInterface(MainActivity.this, "MainActivity");

Above functionalities are help to inject and to create bridge between JavaScript and Java. But if we need to show progress-bar,dialogs etc then we need to add  WebChromeClient to webView which will set chrome handler to webView.
webView.setWebChromeClient(new WebChromeClient());
All the setting of webView are:-
webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(MainActivity.this, "MainActivity");
        webView.setWebChromeClient(new WebChromeClient());

We need one webpage to load in webview which will use for communication.

Create assets directory in project and create webpage.html file in it.
Write some code to HTML page like I write to add 2 input textview and add 1 button.

<!DOCTYPE html>
<html>
<body>
<input type="textview" placeholder="Name" id="name"> <br />
<input type="textview" placeholder="Company" id="company"> <br /> <br />

<button>Show Toast</button>

</body>
</html>

Its time to write some code in JavaScript. We will add <script> in body and create javaScript function which will call Android Java native code. First we will get value from Input type to pass these fileds to java method. In below code MyFunction() funtion will call Java native method.

<script>
function myFunction() {
var name = document.getElementById("name").value;
var company = document.getElementById("company").value;
}
</script>

Now add below code to myFunction(). This line will call showToast() of MainActivity class. because we already had added instance of MainActivity class with name MainActivity in webView.

function myFunction() {
var name = document.getElementById("name").value;
var company = document.getElementById("company").value;

MainActivity.callToast(name,company);

document.getElementById("name").value="";
document.getElementById("company").value="";
}

Call myFunction() from html button like below.
<button onclick="myFunction()">Show Toast</button>

Javascript code is completed for calling native java methods from JavaScript. Now create a showToast() with two params(i.e name & company ) in MainActivity class and add
@JavascriptInterface annotation to method.
 
 @JavascriptInterface
    public void callToast(String name, String company) {

        Toast.makeText(this, "Hi " + name + " !! Wecome to " + company, Toast.LENGTH_LONG).show();
    }

Now we will call JavaScript funtions from native Java class.

First of all we will implement button click listener in java class which will call javascript function of loaded html page in webview.

From button event, get Edit text typed value for passing to javascript function.
 
 public void onBtnClick(View view) {
        String message = editText.getText().toString();
    }

Write below code which will call showAlert() funtion of Javascript with your passing message.

webView.loadUrl("javascript:" + "showAlert" + "(\""+message+"\")");

full code of button click
 public void onBtnClick(View view) {
        String message = editText.getText().toString();
        if (message == null || message.isEmpty()) {
//            Toast.makeText(this, "Message is Empty", Toast.LENGTH_SHORT).show();
            webView.loadUrl("javascript:" + "showAlert" + "(\"Message is Empty\")");
        } else {
            webView.loadUrl("javascript:" + "showAlert" + "(\""+message+"\")");
        }
        editText.setText("");
    }

Java native code is completed, Now add function to JavaScript with name showAlert().
function showAlert(message) {
alert(message);
}

Cheers!!

If you have any query then feel free to post on comment.

You can find code for this blog on below github link.
https://github.com/AmanChugh/WebViewCallBack

Happy coding,,

Comments

Popular posts from this blog

How to change the color of Hamburger icon in Toolbar Android

How to combine two Bitmap in Android

How to do Facebook Login with Custom Button Android