gpt4 book ai didi

javascript - 没有webView的Android中的Kotlin调用Javascript函数

转载 作者:IT老高 更新时间:2023-10-28 13:35:44 24 4
gpt4 key购买 nike

有没有什么方法可以从 Kotlin 调用 JS 函数而无需在 Android 中使用 WebView?

假设如下所述,我在 test.js 文件中有一个 JS 函数 helloJS()

test.js:-

function helloJS(){
return "Hello from JS"
}

现在我想从 Kotlin 文件中调用这个函数,比如

TestClass.kt:-

class TestHello{

fun getHelloFromJS(){
val name = test.helloJS()
}
}

到目前为止,我正在使用 Webview 并将 JS 文件加载到其中并获取结果作为回调

但是,我读到了 Kotlin is interoperable with JS like Java

所以我很想知道是否有任何方法可以在没有 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

关于javascript - 没有webView的Android中的Kotlin调用Javascript函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47515152/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com