如何为 android webview 实现 @JavascriptInterface

How to implement @JavascriptInterface for android webview

目前,我的代码没有给出正常的输出。为什么会这样?

Android:

@JavascriptInterface
fun call(obj:JSONObject?){
    Log.i("webview","$obj")
}

在 Logcat

上输出

I: webview, null

js:

function callAndroid(obj) {
                    androidObj.call(obj);              
            }

callAndroid({
                    key_string: 'test'
                })

实现添加androidObj到webview,成功

Android:
@JavascriptInterface
fun call(str:String?)

js:
androidObj.call('hello')

但参数使用 JSONObject 失败

为 Android WebView 创建 JavaScript 界面需要 3 个步骤。

首先,创建Javascript接口:

@JavascriptInterface
fun call(obj:JSONObject?){
    Log.i("webview","$obj")
}

其次,将 Javascript 界面添加到您的 WebView 并启用 Javascript:

 webView.getSettings().setJavaScriptEnabled(true
 webView.addJavascriptInterface(this, "androidObj")

现在从您的 JS 调用函数:

androidObj.call(obj) 

检查您是否错过了上述任何步骤。