How to execute JavaScript on Android?

后端 未结 10 1382
迷失自我
迷失自我 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 14:38

    The javax.script package is not part of the Android SDK. You can execute JavaScript in a WebView, as described here. You perhaps can use Rhino, as described here. You might also take a look at the Scripting Layer for Android project.

    0 讨论(0)
  • 2020-11-27 14:44

    You can use Rhino library to execute JavaScript without WebView.

    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.

    0 讨论(0)
  • 2020-11-27 14:46

    http://divineprogrammer.blogspot.com/2009/11/javascript-rhino-on-android.html will get you started. ScriptEngine is a java thing. Android doesn't have a JVM but a DalvikVM which is not identical but similar.

    0 讨论(0)
  • 2020-11-27 14:47

    UPDATE 2018: AndroidJSCore has been superseded by LiquidCore, which is based on V8. Not only does it include the V8 engine, but all of Node.js is available as well.

    Original answer: AndroidJSCore is an Android Java JNI wrapper around Webkit's JavaScriptCore C library. It is inspired by the Objective-C JavaScriptCore Framework included natively in iOS 7. Being able to natively use JavaScript in an app without requiring the use of JavaScript injection on a bloated, slow, security-constrained WebView is very useful for many types of apps, such as games or platforms that support plugins. However, its use is artificially limited because the framework is only supported on iOS. Most developers want to use technologies that will scale across both major mobile operating systems. AndroidJSCore was designed to support that requirement.

    For example, you can share Java objects and make async calls:

    public interface IAsyncObj {
        public void callMeMaybe(Integer ms, JSValue callback) throws JSException;
    }
    public class AsyncObj extends JSObject implements IAsyncObj {
        public AsyncObj(JSContext ctx) throws JSException { super(ctx,IAsyncObj.class); }
        @Override
        public void callMeMaybe(Integer ms, JSValue callback) throws JSException {
            new CallMeLater(ms).execute(callback.toObject());
        }
    
        private class CallMeLater extends AsyncTask<JSObject, Void, JSObject> {
            public CallMeLater(Integer ms) {
                this.ms = ms;
            }
            private final Integer ms;
            @Override
            protected JSObject doInBackground(JSObject... params) {
                try {
                    Thread.sleep(ms);
                } catch (InterruptedException e) {
                    Thread.interrupted();
            }
                return params[0];
            }
    
            @Override
            protected void onPostExecute(JSObject callback) {
                JSValue args [] = { new JSValue(context,
                        "This is a delayed message from Java!") };
                 try {
                     callback.callAsFunction(null, args);
                 } catch (JSException e) {
                     System.out.println(e);
                 }
            }
        }
    }
    
    public void run() throws JSException {
        AsyncObj async = new AsyncObj(context);
        context.property("async",async);
        context.evaluateScript(
            "log('Please call me back in 5 seconds');\n" +
            "async.callMeMaybe(5000, function(msg) {\n" +
            "    alert(msg);\n" +
            "    log('Whoomp. There it is.');\n" +
            "});\n" +
            "log('async.callMeMaybe() has returned, but wait for it ...');\n"
        );
    }
    
    0 讨论(0)
  • 2020-11-27 14:48

    I just found the App JavaScript for Android, which is the Rhino JavaScript engine for Java. It can use all Java-classes, so it has BIG potential. The problem is it might be slow, since it is not really optimized (heavy CPU load). There is another JavaScript engine named Nashorn, but that unfortunately doesn't works on Google's DalvikVM Java engine (does not support the optimizations of Oracle Java engine). I hope Google keeps up with that, I would just love it!

    0 讨论(0)
  • 2020-11-27 14:49

    If you want to run some javascript code on chrome browser as per the question copy this code and paste it into address bar:

    data:text/html, <html contenteditable> <title> Notepad </title> <script> alert('Abhasker Alert Test on Mobile'); </script> </html>

    0 讨论(0)
提交回复
热议问题