10

I have a WebView which in the click of an Android button loads some JavaScript into the WebView.

My question is how would I go about passing an Android variable to the JavaScript when it's loaded.

My Current code to load the JavaScript into the WebView

private OnClickListener OnClick_grabit = new OnClickListener() {
    public void onClick(View v) {
        webView.loadUrl("javascript: function loadScript(scriptURL) { 
             var scriptElem = document.createElement('SCRIPT'); 
             scriptElem.setAttribute('language', 'JavaScript'); 
             scriptElem.setAttribute('src', scriptURL); 
             document.body.appendChild(scriptElem);
             } loadScript('http://www.pathtojavascript/javascript.js');");
    }
};

SO I need to pass something to the JavaScript initialize() from Android.

10
  • Is the script located in assets? Or do you need to load it from web? Commented Sep 25, 2013 at 9:50
  • @gunar loaded from the web Commented Sep 25, 2013 at 9:54
  • And the web page is also loaded from the web? Commented Sep 25, 2013 at 9:56
  • so you're loading the web page from the web and then you would like to load a different Javascript to loaded page? Commented Sep 25, 2013 at 9:57
  • @gunar a webpage is laoded into the webview, then when the user clicks a button which is below the webview the above onclick loads a javascript from the web into the webview Commented Sep 25, 2013 at 9:59

5 Answers 5

17

Java Class:

public class JavaScriptInterface {
    Context mContext;
    JavaScriptInterface(Context c) {
        mContext = c;
    }    
    @JavascriptInterface
    public String getFromAndroid() {
        return "This is from android.";
    }
}

Webview code :

WebView webView = (WebView) findViewById(R.id.webview);
webView.setWebChromeClient(new WebChromeClient() {});
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");

Html and javascript:

<input type="button" value="Get from android" onClick="getFromAndroid()" />
<script type="text/javascript">
    var myVar = null;
    function getFromAndroid() {
        myVar = Android.getFromAndroid();
        alert(myVar);
    }
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

This is hands down the best way to do it.
wawww... very very interesting ... with the interface we can connect from variable to the loaded webview....
9

First of all you need to load the script only once (your onClick is loading it every time), then call loadUrl("javascript:initialize(" + myNumber + ");")

2 Comments

Was it that simple? :)
can you expand your answer?
2

The correct syntax that worked for me is

StringBuilder buf=new StringBuilder("javascript:testFunction('"+bar+"','"+foo+"')");
Log.d(TAG, "returned string:"+buf.toString());
mWebView.loadUrl(buf.toString());

2 Comments

And what if bar or foo contains a '?
My one day search end here.. Really best answer compared to others
0

You need to loadUrl in your webView, I got something like this in my previous app:

webView.loadUrl("javascript:wrapJS.functionName("+value+","+value+")"+);

Comments

0

Add the JitPack repository to your build file

allprojects {
      repositories {
        ...
        maven { url 'https://jitpack.io' }
      }
}

Add this to app gradle file:

dependencies {
      compile 'com.github.wendux:WebViewJavascriptBridge:master-SNAPSHOT'
    }

prepare your java script like this:

<!doctype html>
<html><head>
</head><body>
<p>Mehdico</p>
<script>
    function setupWebViewJavascriptBridge(callback) {
        var bridge=window.WebViewJavascriptBridge||window.WKWebViewJavascriptBridge
        if (bridge) { return callback(bridge); }
        var callbacks=window.WVJBCallbacks||window.WKWVJBCallbacks
        if (callbacks) { return callbacks.push(callback); }
        window.WVJBCallbacks=window.WKWVJBCallbacks = [callback];
        if(window.WKWebViewJavascriptBridge){
          window.webkit.messageHandlers.iOS_Native_InjectJavascript.postMessage(null)
        }else{
            var WVJBIframe = document.createElement('iframe');
            WVJBIframe.style.display = 'none';
            WVJBIframe.src = 'https://__bridge_loaded__';
            document.documentElement.appendChild(WVJBIframe);
            setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
        }
    }

    setupWebViewJavascriptBridge(function(bridge) {
            bridge.callHandler('sendToJava', { success:'true' }, function(response) {
            })
    })
    </script>
</body></html>

if you want more handlers just duplicate this lines and change [jsToJava] and data part (success:true)

 bridge.callHandler('sendToJava', { success:'true' }, function(response) {
            })

in your xml:

        <wendu.webviewjavascriptbridge.WVJBWebView
        android:id="@+id/webView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

and java:

webView = findViewById(R.id.webView);
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    webView.setWebViewClient(new AppWebViewClients((ProgressBar) findViewById(R.id.progressBar)));

    if (Build.VERSION.SDK_INT >= 21) { // for fix invalid https certification
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    }

    webView.registerHandler("sendToJava", new WVJBWebView.WVJBHandler() {
        @Override
        public void handler(Object data, WVJBWebView.WVJBResponseCallback callback) {
            Toast.makeText(ActivityPaymentStepBank.this, data.toString(), LENGTH_SHORT).show();
            Log.d("wvjsblog", data.toString());
            callback.onResult(data);
        }
    });

    webView.loadUrl("URL OF YOUR HTML FILE");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.