Trying to call Javascript function from Android after loading of web page gives error: "Uncaught ReferenceError: myFunction is not defined"

Trying to call Javascript function from Android after loading of web page gives error: "Uncaught ReferenceError: myFunction is not defined"

<!doctype html>
<head>
  <meta charset="utf-8">
  <meta name="author" content="Paul Lewis" />
  <meta name="viewport" content="width=device-width">
  <title>NEW ONE</title>
  <style>
    html, body {
      padding: 0;
      margin: 0;
    }
  </style>
</head>
<body>
  <div id="container"></div>
  <script type="text/javascript" src="three.js-master/build/three.js"></script>
<!--     <script src="threejs/js/JSONLoader.js"></script>
 -->
   <script type="module" src="three.js-master/src/loaders/ObjectLoader.js"></script>
    <script type="module" src="three.js-master/src/helpers/GridHelper.js"></script>
    <script type="module" src="three.js-master/src/loaders/JSONLoader.js"></script>
    <script type="text/javascript" src="three.js-master/examples/js/controls/OrbitControls.js"></script>


  <script type="text/javascript">
        function init() 
        {
          function myFunction(data1,data2)
          {
            //Do things
          }
        }
    window.onload = init;
  </script>
</body>
</html>

我已经在 Android 的 Web View 中显示了网页。现在我想定期将数据传递给位于 html 页面中的 myFunction() js 函数。我在 webView 中启用了 javascript,在调用 webView.loadUrl("http://XXXX/index.html"); 之后,我正在调用

js_interface=new WebInterface(this,webView); webView.addJavascriptInterface(js_interface,"Android");

,加载用于与 Javascript 函数交互的接口 class。

WebInterface.java:

public class WebModelInterface {

Context mContext;
WebView webView;

/** Instantiate the interface and set the context */
WebModelInterface(Context c, WebView webView) {
    mContext = c;
    this.webView=webView;
}

/** Show a toast from the web page */
@JavascriptInterface
public void showToast(String toast) {
    Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    Log.e("WebInterface","Called by JavaScript Code!!!");
}


public void setTarget(int finalI,double value){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        webView.evaluateJavascript("javascript:myFunction("+data1+","+data2+");",null);
    }
    else
        webView.loadUrl("javascript:setJointPosition("+finalI+","+value+");");

}

}

我收到错误:Uncaught ReferenceError: setJointPosition is not defined

我也尝试从 chrome 控制台调用该函数,但出现了同样的错误。从脚本中调用函数时,它执行得很好。但是在加载页面并调用它后会出错。请帮忙。谢谢!

解决了!犯了一个愚蠢的错误,没有注意到 JavaScript 代码包含在 init() 函数中。试图直接调用 myFunction,它在 init() 之外不存在。 因此,我删除了 init() 函数并能够从 Android Class.

中正确调用 myFunction