Use V8 JavaScript engine to execute JS lib without web view

前端 未结 4 1222
孤城傲影
孤城傲影 2020-12-05 05:27

I am developing a JavaScript component which is responsible for making requests to the server and dispatching results to the UI. By doing this in JavaScript, I am able to us

4条回答
  •  难免孤独
    2020-12-05 05:59

    I don't know how to use V8, but you can use Rhino library instead. There is no WebView involved too.

    Download Rhino first, unzip it, put the js.jar file under libs folder. It is very small, so you don't need to worry your apk file will be ridiculously large because of this one external jar.

    Here is some simple code to execute JavaScript code.

    Object[] params = new Object[] { "javaScriptParam" };
    
    // Every Rhino VM begins with the enter()
    // This Context is not Android's Context
    Context rhino = Context.enter();
    
    // Turn off optimization to make Rhino Android compatible
    rhino.setOptimizationLevel(-1);
    try {
        Scriptable scope = rhino.initStandardObjects();
    
        // Note the forth argument is 1, which means the JavaScript source has
        // been compressed to only one line using something like YUI
        rhino.evaluateString(scope, javaScriptCode, "JavaScript", 1, null);
    
        // Get the functionName defined in JavaScriptCode
        Object obj = scope.get(functionNameInJavaScriptCode, scope);
    
        if (obj instanceof Function) {
            Function jsFunction = (Function) obj;
    
            // Call the function with params
            Object jsResult = jsFunction.call(rhino, scope, scope, params);
            // Parse the jsResult object to a String
            String result = Context.toString(jsResult);
        }
    } finally {
        Context.exit();
    }
    

    You can see more details at my post.

提交回复
热议问题