[英]How to use Android webview to run javascript that depends on another library/module
We can run simple javascript function (jsCode) like: 我们可以运行简单的javascript函数(jsCode),例如:
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: 但是,如果我的JavaScript依赖于另一个模块或引用了另一个文件,例如:
import { double } from 'mymodule';
Can this be achieved? 能做到吗?
I achieved this by evaluating the external javascript file before evaluating the jsCode 我通过在评估jsCode之前评估外部javascript文件来实现这一目标
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 main.js中的代码使用external_lib.js中定义的变量和函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.