Send Object from Javascript to Kotlin using Webview

Issue

I have loaded a webpage using WebView component and added a JavascriptInterface. Please check the code below,

val webview  WebView(this)
setContentView(webview)
webview.settings.javaScriptEnabled  true
webview.loadUrl(HOME_PAGE_URL)
webview.addJavascriptInterface(JavascriptInterface(),”javascript_bridge”)

And when I call the invoke from Javascript using window.javascript_bridge.showToast(“Information Saved”);

private inner class JavascriptInterface
{
    @android.webkit.JavascriptInterface
    fun showToast(text: String?)
    {
        Log.d("WEBVIEW", text);
    }
}

I am able to call the method from Javascript to Kotlin without any trouble.

But now I want to pass an Object from Javascript to Kotlin like below,

var info  {
    message: “Information Saved”,
    ID: 123456
}

And when I call the invoke from Javascript using window.javascript_bridge.showToast(info);

I tried to change to the data type to Any, but the value passed from Javascript is null

private inner class JavascriptInterface
{
    @android.webkit.JavascriptInterface
    fun showToast(text: Any?)
    {
       Log.d("WEBVIEW", text.toString());
    }
}

Solution

As far as i know, the javaScript interface methods only accepts primitive types of data as parameters (as discussed on this question). If you still want to achieve that, you may serialize the object (to JSON format, for instance) in the javaScript and then Deserialize it in Java. Hope it helps 🙂

Answered By – Rander Gabriel

Leave a Comment