Click here to Skip to main content
15,885,216 members
Articles / Mobile Apps / Android
Tip/Trick

WebView JS Bridge - Android

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
11 Dec 2015CPOL 24.2K   8   1
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)


Written By
Technical Lead
India India
Technology leader with over 10 years of experience and excellent track record of building great products while enabling others to perform their roles more effectively. Having multifaceted technical career with many innovations and success stories. Well recognized for strong leadership and project management abilities while leading cross-functional teams in fast-paced and competitive environments.

I have commendable experience in technologies like Mobile App Development[Native & Hybrid], Android, iOS, Windows Phone, AWS S3/cognito/lambd, golang, C, VC++, Python, C# MVC, ASP.NET, JAVA, J2EE, Spring, SQL Server, MySQL, Oracle etc.

Also fully loaded with client side technologies like OO Java Script, jQuery, NodeJS, KendoUI, Sencha Touch and many more.

Experience in MVC, MVVM, MVP design patterns.

TECH BLOGS:
-----------------------------------------------------------------------------------------------------

https://github.com/swagatblog
https://swagatblog.wordpress.com/
https://hybridmobileappblog.wordpress.com/
http://www.codeproject.com/Members/swagatblog

LINKED-IN Group
-----------------------------------------------------------------------------------------------------
https://www.linkedin.com/groups/5107980

Comments and Discussions

 
GeneralMy vote of 5 Pin
Rajesh Pattanaik2-Jan-16 19:42
Rajesh Pattanaik2-Jan-16 19:42 

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

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