Skip to content

Interface between Java code and javascript code in the webview

rutura edited this page Apr 16, 2017 · 1 revision
  • MinSdk : 1
  • JavascriptInterface allows you to:
    • call javascript code from android java:
    private static final String JS_SETELEMENT =
    "javascript:document.getElementById('%s').value='%s'";
  • call java code from webview javascript:
    private static final String JS_GETELEMENT =
            "javascript:window.BRIDGE"
            + ".storeElement('%s',document.getElementById('%s').value)";
  • The examples look a bit convoluted because we are formating strings to have slightly cleaner code but you could have done something like this which sets some value on the html tag in the dom loaded by the webview on a button click:
    someButton.setOnClickListener( new View.onClickListener(...)
    @Override
    void onClick(View v)
    {
         String elementId = "someTagId";
            String elementValue = "someValue";
            String script = "javascript:document.getElementById(" +elementId +").value=" + elementValue;
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            
            view.evaluateJavascript(script , null);
        } else {
            view.loadUrl(script);
        }
    });
  • Rather than having Java/Android call javascript, we can reverse the roles and have javascript call some java code through a Javascript interface that we attach to our webView.In the snippet below:
    private static final String JS_GETELEMENT =
            "javascript:window.BRIDGE"
            + ".storeElement('%s',document.getElementById('%s').value)";

we are first calling javacript:

    "javascript:window.BRIDGE"

and trough our custom interface, having javacript in turn call our Java/Android function storeElement(..)

    "javascript:window.BRIDGE"
            + ".storeElement('%s',document.getElementById('%s').value)";

to store the retrieved value in SharedPreferences.

Clone this wiki locally