Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run JavaScript method and return parameter

I want to run JavaScript function on my android app,this is how i create the webview:

m_FullJSWebView = new WebView(m_VideoView.getContext());
m_FullJSWebView.loadData(htmltmp, "text/html", "UTF-8");
m_FullJSWebView.getSettings().setJavaScriptEnabled(true);
m_FullJSWebView.addJavascriptInterface(new JavaScriptInterface(m_VideoView.getContext()), "MyAndroid");
m_FullJSWebView.loadUrl("javascript:getValue()");

This is the html:

<html>
  <head>
    <script type="text/javascript">
    function getValue(){
       //return value to Android 
       var val= 50;
       MyAndroid.receiveValueFromJs(val);
    }
    </script>
    <title></title>
  </head>
  <body >
    <form name="ipForm" id="ipForm">
      UserName : <input type="text" name="userName">
      <button type="button" onclick="getValue();">Submit</button>
    </form>
  </body>
</html>

And this is the JavascriptInterface:

public class JavaScriptInterface {
        Context mContext;
        JavaScriptInterface(Context c) {
            mContext = c;
        }
        //add other interface methods to be called from JavaScript

        public void receiveValueFromJs(String str) {
            //do something useful with str
              Toast.makeText(mContext, "Received Value from JS: " + str,Toast.LENGTH_SHORT).show();
        }
}

After i run it on my device the receiveValueFromJs function won't called.Any idea what is the problem?

like image 933
YosiFZ Avatar asked May 21 '26 08:05

YosiFZ


1 Answers

From the doc:

Note that injected objects will not appear in JavaScript until the page is next (re)loaded.

Which means that you must change your methods order like that:

m_FullJSWebView = new WebView(m_VideoView.getContext());
m_FullJSWebView.addJavascriptInterface(new JavaScriptInterface(m_VideoView.getContext()), "MyAndroid");
m_FullJSWebView.loadData(htmltmp, "text/html", "UTF-8");
m_FullJSWebView.getSettings().setJavaScriptEnabled(true);
m_FullJSWebView.loadUrl("javascript:getValue()");

edit (2nd issue)

the name parameter in the addJavascriptInterface is name of the java object in the javascript. it is the object on which to call the methods from the javascript.

Therefore, your call should be:

m_FullJSWebView.loadUrl("javascript:MyAndroid.getValue()");
like image 91
njzk2 Avatar answered May 22 '26 22:05

njzk2