jiawen jiawen - 2 months ago 7
Android Question

How to use Android webview to run javascript that depends on another library/module

We can run simple javascript function (jsCode) like:

function() {
return "test"
}


in webview:

String js = "(" + jsCode + ") ();"
mWebView.evaluateJavascript(js, new ValueCallback<String>() {
@Override
public void onReceiveValue(String s) {
Log.d("return value: ", s); // Returns the value from the function
}
});


But what if my javascript depends on another module or reference another file like:

import { double } from 'mymodule';


Can this be achieved?

Answer

I achieved this by evaluating the external javascript file before evaluating the jsCode

private String[] jsFiles = {"external_lib.js", "main.js"};

private void evaluateJS() {
        try {
            String js = readFromAssets(jsFiles[fileIndex]);
            Log.e(TAG, "evaluating: " + jsFiles[fileIndex]);
            mWebView.evaluateJavascript(js, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String s) {
                    fileIndex++;
                    if (fileIndex == jsFiles.length) {
                        // we have evaluated the last javascript file
                        Log.e("return value: ", s); // Returns the value from the function
                        return;
                    }
                    evaluateJS();
                }
            });
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

the code in main.js uses variables and functions that are defined in external_lib.js

Comments