Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable from Android to JavaScript launched in WebView

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.

like image 568
Zac Powell Avatar asked Sep 25 '13 09:09

Zac Powell


2 Answers

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>
like image 66
Taner Avatar answered Oct 07 '22 13:10

Taner


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

like image 38
gunar Avatar answered Oct 07 '22 13:10

gunar