I have already seen a similar question in stackoverflow, but I want a better explained answer to this question. I am new to android development and I am trying to figure out how to pass a variable in my java code to the javascript in index.html. Any suggestions are welcomed.
How to pass variable from java to javascript in Android webview?
288 Views Asked by Anandakrishnan At
2
There are 2 best solutions below
0
On
Try with the following code may be it will help you.
//Android WebView code
JavaScriptInterface JSInterface;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
wv = (WebView)findViewById(R.id.webView1);
wv.getSettings().setJavaScriptEnabled(true);
// register class containing methods to be exposed to JavaScript
JSInterface = new JavaScriptInterface();
wv.addJavascriptInterface(JSInterface, "JSInterface");
wv.loadUrl("file:///android_asset/myPage.html");
}
public class JavaScriptInterface {
@android.webkit.JavascriptInterface
public void showToast(String msg)
{
Log.d("TAG",msg);
}
}
//This is your web page
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function init()
{
var testVal = 'Android Toast!’;
Android.showToast(testVal);
}
</script>
</head>
<body>
<div style="clear: both;height: 3px;"> </div>
<div>
<input value="submit" type="button" name="submit"
id="btnSubmit" onclick="javascript:return init();" />
</div>
</body>
</html>
You could try to use JsBridge library: