Skip to content Skip to sidebar Skip to footer

How Do I Make JavaScript-Java Communication Sync In Android WebView?

I've got WebView, JS code inside it. Also I have interface to allow Java method invocation from WebView to Java code. I need to pass data from JS to Java. To do so: webView.loadUrl

Solution 1:

The only (hacky) solution that I've come across is using a one second delay after calling the loadUrl. You may use the addJavaSriptInterface() to do so.

or if the JS processing takes too long you have to use callbacks

<input type="button" value="Say hello" onClick="callYourCallbackFunctionHere('Hello Android!')" />

<script type="text/javascript">
    function callYourCallbackFunctionHere(toast) {
        Android.callAndroidCallback(toast);
    }
</script>

public class JavaScriptInterface {
    Context mContext;

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

    /** Show a toast from the web page */
    public void callAndroidCallback(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
}

Post a Comment for "How Do I Make JavaScript-Java Communication Sync In Android WebView?"