最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

android - Send Object from Javascript to Kotlin using Webview - Stack Overflow

programmeradmin1浏览0评论

I have loaded a webpage using WebView ponent 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());
    }
}

I have loaded a webpage using WebView ponent 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());
    }
}
Share Improve this question asked Sep 11, 2019 at 1:54 PerseusPerseus 1,5884 gold badges30 silver badges55 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

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 :)

发布评论

评论列表(0)

  1. 暂无评论