Android non-WebView calls js code

1. The third-party package download address: https://github.com/mozilla/rhino

Get rhino-1.7.12

2. Introduce into the project

3. Tools

/**
 *
 * @param js js源码 "function test(a,b){return a+b;}"
 * @param functionName method name
 * @param functionParams parameters
 * @return
 */
public static String callFunction(String js,String functionName,Object[] functionParams){
    if(TextUtils.isEmpty(js)) return "";
    js = js.replace("\\r\\n",""); //Remove the escape character
    Context rhino= Context.enter();
    rhino.setOptimizationLevel(-1);
    try {
        Scriptable scope=rhino.initStandardObjects();
        rhino.evaluateString(scope,js, null, 0,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();
    }catch (Exception e){

    }

    Context.exit();
    return "";

}

Guess you like

Origin blog.csdn.net/wuqiqi1992/article/details/108417094