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.
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>
First of all you need to load the script only once (your onClick
is loading it every time), then call loadUrl("javascript:initialize(" + myNumber + ");")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With