Essential Android WebView edit forum

Communication from Javascript to Java Android

Android Activity

package com.example.myapp;

import android.os.Bundle;
import android.app.Activity;
import android.webkit.WebView;

public class WebViewActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        WebView webView = new WebView(this);
        setContentView(webView);

       /* 
        *   Note the label Android, this is used in the Javascript side of things
        *   You can of course change this.
        */
        webView.addJavascriptInterface(new JavascriptHandler(), "Android");
    
        webView.loadUrl("http://example.com");
    }
}

Java Javascript Handler

import android.webkit.JavascriptInterface;

public class JavascriptHandler {

    /**
     *  Key point here is the annotation @JavascriptInterface
     *
     */
    @JavascriptInterface
    public void jsCallback() {
       // Do something
    }

    @JavascriptInterface
    public void jsCallbackTwo(String dummyData) {
       // Do something
    }
}

Web Page, Javascript call

<script>
... 
Android.jsCallback();
...
Android.jsCallback('hello test');
...
</script>

Extra Tip

Passing in a complex data structure, a possible solution is use JSON.

Android.jsCallback('{ "fake-var" : "fake-value", "fake-array" : [0,1,2] }');

On the Android side use your favorite JSON parser ie: JSONObject


Table Of Contents
20 WebView
39 ACRA
64 Menu
112 Loader
119 Xposed
132 Colors
135 Fresco
140 AdMob
147 Button
156 Vk SDK
170 XMPP
176 OpenCV
200 FileIO
203 Moshi
217 Paint
231 AIDL
241 JCodec
243 Okio
255 Looper
  ↑ ↓ to navigate     ↵ to select     Esc to close