Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Javascript bridge in android

Im just trying to communicate my java app with the content on the webview .

In detail , may be just showing a toast on button click ?

After searching on google and doing some research , ended up with the following code .

P.S : - Im using Android Studio , is there any external library i need to compile inorder to get things done ? or something else ?

Following is my WebviewActivity code:-

public class WebviewActivity extends AppCompatActivity {

private static final String TAG = "Main";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_webview);
    //WebView Object
    WebView browser;
    browser=(WebView)findViewById(R.id.webView);
    //Enable Javascript
    browser.getSettings().setJavaScriptEnabled(true);
    //Inject WebAppInterface methods into Web page by having Interface 'Android'
    browser.addJavascriptInterface(new WebAppInterface(this), "Android");
    browser.loadUrl("http://www.somewebsite.com/app/form.html");
}
//Class to be injected in Web page
public class WebAppInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    WebAppInterface(Context c) {
        mContext = c;
    }

    /**
     * Show Toast Message
     * @param toast
     */
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }

    /**
     * Show Dialog
     * @param dialogMsg
     */
    public void showDialog(String dialogMsg){
        AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();

        // Setting Dialog Title
        alertDialog.setTitle("JS triggered Dialog");

        // Setting Dialog Message
        alertDialog.setMessage(dialogMsg);

        // Setting alert dialog icon
        //alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(mContext, "Dialog dismissed!", Toast.LENGTH_SHORT).show();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    /**
     * Intent - Move to next screen
     */
    public void moveToNextScreen(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
        // Setting Dialog Title
        alertDialog.setTitle("Alert");
        // Setting Dialog Message
        alertDialog.setMessage("Are you sure you want to leave to next screen?");
        // Setting Positive "Yes" Button
        alertDialog.setPositiveButton("YES",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        //Move to Next screen

                    }
                });
        // Setting Negative "NO" Button
        alertDialog.setNegativeButton("NO",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // Cancel Dialog
                        dialog.cancel();
                    }
                });
        // Showing Alert Message
        alertDialog.show();
     }
  }
}

form.html:-

 <html>
 <head>
  <style>
  body{
 background-color: #FA5858;
color:#fff;
  }
input{
background-color: #F7D358;
width: 300px;
padding:10px;
color: #000;
 }
 div#content{
 padding:20px;
 background-color: #F7D358;
  color: #000;
 }
 </style>
 <script type="text/javascript">
  function showAndroidToast(toastmsg) {
    Android.showToast(toastmsg);
   }
 function showAndroidDialog(dialogmsg) {
      Android.showDialog(dialogmsg);
   }
  function moveToScreenTwo() {
    Android.moveToNextScreen();
   }
 </script>
  </head>
  <body>
  <center>
  <h3>Binding JavaScript code to Android code</h3>
      <div id="content">
//some content here
         </div>
     <div>
   Here are few examples:
     </div>
  <div>
       <input type="button" value="Make Toast" onClick="showAndroidToast('Toast made by Javascript')" /><br/>
       <input type="button" value="Trigger Dialog" onClick="showAndroidDialog('This dialog is triggered by Javascript ')" /><br/>
        <input type="button" value="Take me to Next Screen" onClick="moveToScreenTwo()" />
          </div>
      </center>
     </body>
    </html>

I have this above code , but it is not working in android-studio , tried all posiblities so finally posted my question here .

My study for this :-

https://developer.android.com/guide/webapps/webview.html
https://developer.android.com/reference/android/webkit/WebView.html
http://stackoverflow.com/questions/4325639/android-calling-javascript-functions-in-webview
like image 775
Vikrant Avatar asked Sep 23 '16 09:09

Vikrant


People also ask

Can you use JavaScript in an Android app?

Can we use JavaScript for Android? Yes, of course! The Android ecosystem supports the concept of hybrid apps, which is a wrapper over the native platform. It mimics the UI, UX, and all kinds of hardware and network interactions, just like how you would use a native Android app.

What is a JavaScript bridge?

The Bridge pattern allows two components, a client and a service, to work together with each component having its own interface. Bridge is a high-level architectural pattern and its main goal is to write better code through two levels of abstraction. It facilitates very loose coupling of objects.

How JavaScript is used in Android?

The JavaScript can alter and change the CSS and HTML as well as validate, manipulate and calculate data. Meteor is the platform to build mobile and web apps by using a JavaScript codebase. Creating new mobile apps with JavaScript is quite easy and it may suitable for all platforms such as Android and IOS.

How do I enable JavaScript on Android WebView?

Enable JavaScript JavaScript is disabled in a WebView by default. You can enable it through the WebSettings attached to your WebView .You can retrieve WebSettings with getSettings() , then enable JavaScript with setJavaScriptEnabled() . WebView myWebView = (WebView) findViewById(R.id.webview);


1 Answers

Your methods inside WebAppInterface class are missing the @JavascriptInterface annotation.

Your WebAppInterface class should be like this,

public class WebAppInterface {
    Context mContext;

    WebAppInterface(Context c) {
        mContext = c;
    }

    @JavascriptInterface
    public void showToast(String toast) {
    }

    @JavascriptInterface
    public void showDialog(String dialogMsg){
    }

    @JavascriptInterface
    public void moveToNextScreen(){
    }

}

Edit

Don't forget to limit your app to API17+ when loading web content into the WebView, otherwise your App will be vulnerable to attacks. Read @Robert's comment below.

like image 191
K Neeraj Lal Avatar answered Nov 15 '22 15:11

K Neeraj Lal