How to execute JavaScript on Android?

后端 未结 10 1432
迷失自我
迷失自我 2020-11-27 14:38

I have code which uses ScriptEngineManager, ScriptEngine class for executing JavaScript code using Java. But it works fine in Java SE, and doesn\'t work in Android - SDK sh

10条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 15:04

    I was also looking for a way to run javascript on Android and came across j2v8 library. This is a java wrapper for Google's v8 engine.

    To use it add a dependency:

    compile 'com.eclipsesource.j2v8:j2v8_android:3.0.5@aar'
    

    It has pretty simple api, but I haven't found any docs online apart from javadoc in maven repository. The articles on their blog are also useful.

    Code sample from this article:

    public static void main(String[] args) {
        V8 runtime = V8.createV8Runtime();
    
        int result = runtime.executeIntegerScript(""
            + "var hello = 'hello, ';\n"
            + "var world = 'world!';\n"
            + "hello.concat(world).length;\n");
    
        System.out.println(result);
    
        runtime.release();
    }
    

提交回复
热议问题