簡體   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