Fam Wencong, Kenneth

My Diary

Binding JavaScript Code To Android Code

Published: Monday, May 11, 2020

When developing a web application that’s designed specifically for the WebView in your Android app, you can create interfaces between your JavaScript code and client-side Android code. For example, your JavaScript code can call a method in your Android code to display a Dialog, instead of using JavaScript’s alert() function.

To bind a new interface between your JavaScript and Android code, call addJavascriptInterface(), passing it a class instance to bind to your JavaScript and an interface name that your JavaScript can call to access the class.


    private WebView myWebView;
    protected void onCreate(Bundle savedInstanceState) {
        myWebView = (WebView) findViewById(R.id.webview);
        myWebView.setWebViewClient(new MyWebViewClient());
        WebSettings webSettings = myWebView.getSettings();
        myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");

    private class WebAppInterface {
        Context mContext;
        WebAppInterface(Context c) {
            mContext = c;
        public void alert(String msg) {
            Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();


<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
    function showAndroidToast(v) {