1

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.

Anandakrishnan
  • 349
  • 5
  • 10

2 Answers2

0

You could try to use JsBridge library:

https://github.com/lzyzsd/JsBridge
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
0

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>
Dharmender Manral
  • 1,504
  • 1
  • 6
  • 7