繁体   English   中英

如何从 JavaScript 调用 Kotlin function

[英]How to call a Kotlin function from JavaScript

I am trying to fill a TextView located inside WebView (in Android) with random email generated by Kotlin function using JavaScript but not found any solution.

我的Kotlin function用于生成随机 email 地址

fun getSaltString(): String? {
    val SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
    val salt = StringBuilder()
    val rnd = Random()
    while (salt.length < 7) { // length of the random string.
        val index = (rnd.nextFloat() * SALTCHARS.length) as Int
        salt.append(SALTCHARS[index])
    }
    return salt.toString()
}

这是使用 Kotlin getSaltString()+"@gmail.com"对上述 function 的调用,但我不知道如何从JavaScript调用它?

到目前为止我的JavaScript通话

myWebView.loadUrl("javascript:(function(){document.getElementById(\"user_email_login\").value = \"I don't know how to call @gmail.com\";\n})()");

任何帮助将不胜感激。 提前致谢:)

我没有时间测试这个,但希望它是正确的。 您需要一个 class 包含您希望能够从 JS 调用的函数。 此 class 的一个实例将绑定到您的 WebView。 class 中的每个 function 都需要在其前面加上注解@JavascriptInterface

我使您的 function 的内容更加简洁,仅作为提示。

class WebAppInterface {

    @JavascriptInterface
    fun getSaltString(): String = buildString {
        val saltChars = ('A'..'Z').toList() + ('0'..'9').toList()
        repeat(7) {
            append(saltChars.random())
        }
    }

}

然后使用 webview 注册此 class 的实例。 您在此处传递的任何字符串名称都将是您在 JS 中预先调用的名称:

myWebView.addJavascriptInterface(WebAppInterface(), "Android")
myWebView.loadUrl("javascript:(function(){document.getElementById(\"user_email_login\").value = Android.getSaltString() + \"@gmail.com\";\n})()");

我找到了解决方案,至少在我的情况下它非常简单。

我需要填写由Kotlin Function随机生成的 Email TextBox In (Android WebView)。

我的 Function 用于生成随机文本

fun getSaltString(): String? {
    val SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
    val salt = StringBuilder()
    val rnd = Random()
    while (salt.length < 7) { // length of the random string.
        val index = (rnd.nextFloat() * SALTCHARS.length).toInt()
        salt.append(SALTCHARS[index])
    }
    return salt.toString()
}

现在我声明了两个variables来保存我的随机 email 的值。

 val temporaryEmailaddress: String? = getSaltString()
 val EmailAddressFinal: String? = "$temporaryEmailaddress@gmail.com"

最后,对EmailAddressFinal变量的简单调用就完成了。 :)

myWebView.loadUrl("javascript:(function(){document.getElementById(\"user_email_login\").value = \"$EmailAddressFinal\";\n})()");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM