Passing String variable from Java to JavaScript via Webview (vice versa)

I am trying to make an app where two users can interact through webview. I want to get a String variable from javascript to Java so that I can save it in my Sqlite database.(And vice versa)

Upvotes: 2

Views: 697

Answers (1)

Maulik Hirani
Maulik Hirani

Reputation: 1913

Calling Java/Kotlin code from JavaScript

There's a feature of Android WebView called Javascript Interface which is what you should look for.

It allows you to run your java/kotlin code from your javascript code.

You can define an interface by

val webView: WebView = findViewById(R.id.webview)
webView.addJavascriptInterface(WebAppInterface(this), "Android")

Here, WebAppInterface defines the methods which you want to be called from javascript.

/** Instantiate the interface and set the context  */
class WebAppInterface(private val mContext: Context) {
     /** Show a toast from the web page  */
     @JavascriptInterface
     fun showToast(toast: String) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show()
     }
}

"Android" here is an interface added to your webview and can be used in your javascript code to call Android methods.

Once this is done, you can call the methods from your javascript,

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
    Android.showToast(toast);
}
</script>

Keep in mind that the interface callbacks are not always called in main thread. So, if you want to perform any UI operations, make sure you use runOnUiThread.

Calling JavaScript function from Java/Kotlin code

There's a feature of Android WebView called Evaluate Javascript for API 19+ to call your javascript functions from java/kotlin code.

For example, for the following javascript:

<script type="text/javascript">
function printName(name) {
    console.log(name); 
}
</script>

You can write this code to call this JS function:

yourWebview.evaluateJavascript("printName(\'TEST\')")

Upvotes: 5

Related Questions