Search code examples
javascriptkotlinandroid-webview

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.

My Kotlin function for generating random email address

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()
}

And here is the call to the above function using Kotlin getSaltString()+"@gmail.com" but what I don't know how to call it from JavaScript?

My JavaScript call so far

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

Any help would be highly appreciated. Thanks in advance:)


Solution

  • I don't have time to test this, but hopefully it's right. You need a class that contains your function(s) that you want to be able to call from JS. An instance of this class will be bound to your WebView. Each function in the class needs the annotation @JavascriptInterface before it.

    I made the content of your function more concise, just as a tip.

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

    Then you register an instance of this class with the webview. Whatever String name you pass here will be what you prepend calls with in your JS:

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