Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Android

WebView JS Bridge - Android

5.00/5 (4 votes)
11 Dec 2015CPOL 24.9K  
WebView JS Bridge - Android

Introduction

Sample Android app with JS <-> WebView <-> Native communication. This application explains about base communication between JavaScript and Native code in Android. Also, this sample app has WebView implementation using JavascriptInterface implementation.

Background

How does hybrid mobile app framework work behind the scenes? How does WebView communicate with JS/Web pages?

Using the Code

The below steps will let us create a base framework which allows a native app to communicate with JavaScript or WebView components.

STEP 1: Create JavascriptInterface Class

JavaScript
//
// Interface Functions
//
JavaScript
@JavascriptInterface
public void yourInterfaceFunction(String data) {
    Toast.makeText([your_context], data, Toast.LENGTH_SHORT).show();
}
JavaScript
@JavascriptInterface
public void showDialog(String dialogMsg){
    AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();

    alertDialog.setTitle("My Title");
   
    alertDialog.setMessage(dialogMsg);   
   
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(mContext, "Some Message!", Toast.LENGTH_SHORT).show();
        }
    });
 
    alertDialog.show();
}

STEP 2: Create WebView Activity

C#
//
// Webview Activity
//
C#
public class WebViewActivity extends Activity {

     private static final String URL = "file:///android_asset/index.html";
    private WebView mWebView;
    private ProgressDialog progress;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jswebview);
        showLoadingDialog();
        mWebView = (WebView) findViewById(R.id.activity_main_webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                dismissLoadingDialog();
            }
        });

        //Inject WebAppInterface methods into Web page by having Interface 'JSBridgePlugin'
        mWebView.addJavascriptInterface(new JSBridge(this,mWebView), "JSBridgePlugin");
        refreshWebView();
    }

    public void showLoadingDialog() {

        if (progress == null) {
            progress = new ProgressDialog(this);
            progress.setTitle("JS Bridge");
            progress.setMessage("Loading Webview Content....");
        }
        progress.show();
    }

    public void dismissLoadingDialog() {

        if (progress != null && progress.isShowing()) {
            progress.dismiss();
        }
    }

    private void refreshWebView() {
        mWebView.loadUrl(URL);
    }
}

STEP 3: JS Functions to Call Native Implementations

JavaScript
//
// JS Implementations
//
JavaScript
var JSPlugin = new function() {

    this.yourInterfaceFunction= function(msg) {
             JSBridgePlugin.yourInterfaceFunction(msg);
       };

       this.showDialog=function(msg) {
             JSBridgePlugin.showDialog(msg);
       };

        this.withCallback=function(msg) {
                    JSBridgePlugin.withCallback(msg, 'JSPluginCallbackHandler.readData');
              };
};

function JSPluginCallbackHandler(data){
alert(data);
};

STEP 4: Manifest Settings

C#
//
// Should add below settings in AndroidManifest file
//
HTML
<uses-permission android:name="android.permission.INTERNET" />

STEP 5: Assets Directory

//
// Assets Structure
//
-app
    -assets
         - Scripts
              - JS files
         - index.html

The complete sample app and source code can be downloaded from https://github.com/swagatblog/WebViewJSBridgeAndroid.

License

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