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

问题描述 投票:10回答:4

有没有什么方法可以在没有WebView的情况下从Kotlin调用JS函数?

让我们说如下所述我在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上使用它

javascript android webview kotlin kotlin-js-interop
4个回答
9
投票

这是不可能直接的,但我找到了一个库Execute JavaScript in Android without WebView来实现这一目标。

仔细阅读该博客并按照以下步骤操作。

将你的JavaScript文件(test.js)保存在android项目的assets文件夹中。

我已将该代码转换为Kotlin。

CallJavaScript.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

6
投票

这是不可能的。您不得将语言与平台混淆。

Kotlin可以像JS一样与JS互操作

意味着Kotlin / JS可以在Javascript平台(Node.js或浏览器)中使用和使用。编译(转换)成js的Kotlin代码能够调用其他js文件。外部Js代码可以从Kotlin调用js代码构建。这是与JS的互操作性。

Kotlin / JS和Kotlin / JVM之间没有互操作性。

enter image description here


0
投票

Kt看起来像JS,但事实并非如此。它将针对Android运行时进行编译,而不是针对java脚本引擎进行编译。

JS代码需要JS运行时,但它不在Android Runtime中。

即你不能直接在Android的Java / Kt代码中运行JS。


0
投票

我不是Kotlin的专业人士,但Java对我来说是个馅饼。你可以在Java中实现的任何东西都可以在Kotlin中实现,并且为了执行Javascript代码,我使用rhino来完成这项工作比使用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();
}
© www.soinside.com 2019 - 2024. All rights reserved.