![](/img/trans.png)
[英]Android call javascript function with parameters without webview
[英]Kotlin Call Javascript function in Android without webView
有什么方法可以在 Android 中没有 WebView 的情况下从 Kotlin 调用 JS 函数?
假设如下所述,我在test.js文件中有一个 JS 函数helloJS()
,
test.js:-
function helloJS(){
return "Hello from JS"
}
现在我想从 Kotlin 文件中调用这个函数,比如
测试类.kt:-
class TestHello{
fun getHelloFromJS(){
val name = test.helloJS()
}
}
到目前为止,我正在使用 Webview 并将 JS 文件加载到其中并以回调的形式获取结果
但是,我读到Kotlin 可以像 Java 一样与 JS 互操作
所以我很想知道我们是否可以在没有 webView 的情况下在 Android 上使用它
这是不可能的,但我找到了一个库Execute JavaScript in Android without WebView来实现这一点。
仔细阅读该博客并按照以下步骤操作。
将您的JavaScript
文件 ( test.js
) 保存在 android 项目的 assets 文件夹中。
我已将该代码转换为 Kotlin。
调用JavaScript.jks
import org.mozilla.javascript.Context
import org.mozilla.javascript.Function
import java.io.InputStreamReader
object CallJavaScript {
fun callFunction(mContext: android.content.Context): Any? {
var jsResult: Any? = null
val params = arrayOf<Any>("")
// Every Rhino VM begins with the enter()
// This Context is not Android's Context
val rhino = Context.enter()
// Turn off optimization to make Rhino Android compatible
rhino.optimizationLevel = -1
try {
val 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
val assetManager = mContext.assets
try {
val input = assetManager.open("test.js")
val targetReader = InputStreamReader(input)
rhino.evaluateReader(scope, targetReader, "JavaScript", 1, null)
} catch (e: Exception) {
e.printStackTrace()
}
// Get the functionName defined in JavaScriptCode
val obj = scope.get("helloJS", scope)
if (obj is Function) {
// Call the function with params
jsResult = obj.call(rhino, scope, scope, params)
// Parse the jsResult object to a String
val result = Context.toString(jsResult)
}
} finally {
Context.exit()
}
return jsResult
}
}
将此行添加到build.gradle
:
implementation 'org.mozilla:rhino:1.7R4'
在您的assets
文件夹中,创建一个名为test.js
的文件:
function helloJS()
{
return "Hello from JS";
}
现在只需从 Activity 调用上面的函数。
Log.e("JS : ", CallJavaScript.callFunction(this).toString());
输出:
E/JS :: Hello from JS
Kt 看起来像 JS,但它不是。 它将为 Android 运行时编译,而不是为 java 脚本引擎编译。
JS 代码需要 JS 运行时,但它不在 Android 运行时中。
即你不能直接在 Android 的 Java/Kt 代码中运行 JS。
我不是 Kotlin 的专业人士,但 Java 对我来说是一个馅饼。 你可以在 Java 中实现的任何东西都可以在 Kotlin 中实现,为了执行 Javascript 代码,我使用犀牛,它比使用 webview 更容易实现它:
try {
Scriptable scope = rhino.initStandardObjects();
rhino.evaluateString(scope, javaScriptCode, "JavaScript", 1, null);
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.