Method instances that let Java execute javascript using Rhino

  • 2020-04-01 02:36:27
  • OfStack

Download the Rhino (link: https://developer.mozilla.org/en-US/docs/Rhino)

Copy the js.jar to the project project

Implementation from Java to execute the function in js, from js to call the method in Java, code:


public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView text1 = (TextView) findViewById(android.R.id.text1);
        TextView text2 = (TextView) findViewById(android.R.id.text2);
        text1.setText(runScript(JAVA_CALL_JS_FUNCTION, "Test", new String[] {}));
        text2.setText(runScript(JS_CALL_JAVA_FUNCTION, "Test", new String[] {}));
    }
    
    private static final String JAVA_CALL_JS_FUNCTION = "function Test(){ return ' Farmer uncle  java call js Rhino'; }";
    
    private static final String JS_CALL_JAVA_FUNCTION = //
    "var ScriptAPI = java.lang.Class.forName("" + MainActivity.class.getName() + "", true, javaLoader);" + //
        "var methodRead = ScriptAPI.getMethod("jsCallJava", [java.lang.String]);" + //
        "function jsCallJava(url) {return methodRead.invoke(null, url);}" + //
        "function Test(){ return jsCallJava(); }";
    
    public String runScript(String js, String functionName, Object[] functionParams) {
        Context rhino = Context.enter();
        rhino.setOptimizationLevel(-1);
        try {
            Scriptable scope = rhino.initStandardObjects();
            ScriptableObject.putProperty(scope, "javaContext", Context.javaToJS(MainActivity.this, scope));
            ScriptableObject.putProperty(scope, "javaLoader", Context.javaToJS(MainActivity.class.getClassLoader(), scope));
            rhino.evaluateString(scope, js, "MainActivity", 1, null);
            Function function = (Function) scope.get(functionName, scope);
            Object result = function.call(rhino, scope, scope, functionParams);
            if (result instanceof String) {
                return (String) result;
            } else if (result instanceof NativeJavaObject) {
                return (String) ((NativeJavaObject) result).getDefaultValue(String.class);
            } else if (result instanceof NativeObject) {
                return (String) ((NativeObject) result).getDefaultValue(String.class);
            }
            return result.toString();//(String) function.call(rhino, scope, scope, functionParams);
        } finally {
            Context.exit();
        }
    }
    public static String jsCallJava(String url) {
        return " Farmer uncle  js call Java Rhino";
    }
}

Note that js.jar may not be obfuscated when it is obfuscated, as described in article 4.1.


Related articles: