Use V8 JavaScript engine to execute JS lib without web view

前端 未结 4 1214
孤城傲影
孤城傲影 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 06:09

    I found this really nifty open source ECMAScript compliant JS Engine completely written in C called duktape

    Duktape is an embeddable Javascript engine, with a focus on portability and compact footprint.

    You'd still have to go through the ndk-jni business, but it's pretty straight forward. Just include the duktape.c and duktape.h from the distributable source here(If you don't want to go through the build process yourself) into the jni folder, update the Android.mk and all that stuff.

    Here's a sample C snippet to get you started.

    #include "duktape.h"
    
    JNIEXPORT jstring JNICALL
    Java_com_ndktest_MainActivity_evalJS
    (JNIEnv * env, jobject obj, jstring input){
        duk_context *ctx = duk_create_heap_default();
        const char *nativeString = (*env)->GetStringUTFChars(env, input, 0);
        duk_push_string(ctx, nativeString);
        duk_eval(ctx);
        (*env)->ReleaseStringUTFChars(env, input, nativeString);
        jstring result = (*env)->NewStringUTF(env, duk_to_string(ctx, -1));
        duk_destroy_heap(ctx);
        return result;
    }
    

    Good luck!

提交回复
热议问题