简体   繁体   English

如何为 android webview 实现 @JavascriptInterface

[英]How to implement @JavascriptInterface for android webview

Currently, my code is not giving normal output.目前,我的代码没有给出正常的 output。 Why is this so?为什么会这样?

Android: Android:

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

output on Logcat Logcat 上的 output

I: webview, null我:webview,null

js: js:

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

callAndroid({
                    key_string: 'test'
                })

it is implemented add androidObj to webview,that is successful实现了将androidObj添加到webview,即成功

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

js:
androidObj.call('hello')

but parameter use JSONObject is failed但参数使用 JSONObject 失败

There are 3 steps to create JavaScript interface for Android WebView.为 Android WebView 创建 JavaScript 接口有 3 个步骤。

First, Create the Javascript interface:首先,创建Javascript接口:

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

Second, Add Javascript interface to your WebView and enable Javascript:其次,将 Javascript 接口添加到您的 WebView 并启用 Javascript:

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

Now call the function from your JS:现在从你的 JS 调用 function:

androidObj.call(obj) 

Check if you have missed any of the above steps.检查您是否错过了上述任何步骤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM