如何从java代码调用javascript函数

时间:2012-07-31 11:42:36

标签: java javascript android cordova

我试图从java类调用javascript函数,但是我遇到了这些错误:

-Could not find method sun.misc.Service.installedProviders, referenced from method javax.script.ScriptEngineManager.initEngines

-Could not find method sun.misc.Service.providers, referenced from method javax.script.ScriptEngineManager.initEngines

-Could not find method sun.misc.Service.installedProviders, referenced from method javax.script.ScriptEngineManager.initEngines

-java.lang.VerifyError: javax.script.ScriptEngineManager

这里是代码:

    public  void sendResult(){
    ScriptEngineManager manager = new ScriptEngineManager();
                    ScriptEngine engine = manager.getEngineByName("js");

                    String script = "function send() {"+"var id_result = window.MyPGP.getResult();"+                            
                            "document.getElementById('id_result').value = id_result;"+"console.log(\"change the box value\");";

                    try {
                        engine.eval(script);

                        Invocable invocableEngine = (Invocable) engine;

                        invocableEngine.invokeFunction("send");


   } catch (ScriptException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }  catch (Exception e) {
                    e.printStackTrace();
                }

我正在努力做的是,当付款完成后,此功能将在此课程的其他方法中调用,以获得付款结果,并将其打印在主html的框中。

3 个答案:

答案 0 :(得分:0)

 ScriptEngine engine = manager.getEngineByName("JavaScript");

这有用吗?

答案 1 :(得分:0)

你可以做这样的事情

super.loadUrl("file:///android_asset/www/index.html", 20000);
super.loadUrl("javascript: { var pageFlag = '" + flag + "';}"); // Your Javascript function here

答案 2 :(得分:0)

使用此代码

import javax.script.*;

public class InvokeScriptFunction {
    public static void main(String[] args) throws Exception {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");

        // JavaScript code in a String
        String script = "function hello(name) { print('Hello, ' + name); }";
        // evaluate script
        engine.eval(script);

        // javax.script.Invocable is an optional interface.
        // Check whether your script engine implements or not!
        // Note that the JavaScript engine implements Invocable interface.
        Invocable inv = (Invocable) engine;

        // invoke the global function named "hello"
        inv.invokeFunction("hello", "Scripting!!" );
    }
}
祝你好运