在 Android 上使用 addJavascriptInterface() 传递 JavaScript 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2250917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:14:41  来源:igfitidea点击:

Passing a JavaScript object using addJavascriptInterface() on Android

javajavascriptandroid

提问by pheelicks

Is it possible to pass a JavaScript object from JavaScript to Java using addJavascriptInterface()? Something along these lines:

是否可以使用 addJavascriptInterface() 将 JavaScript 对象从 JavaScript 传递到 Java?沿着这些路线的东西:

var javaScriptObject = {"field1":"string1", "field2":"string2"};
JavaScriptInterface.passObject(javaScriptObject);

How would such a call be captured on the Java side? I have no problem setting up the interface to send a string, but when I send an object, I receive null on the Java end.

在 Java 端如何捕获这样的调用?我设置接口发送字符串没有问题,但是当我发送一个对象时,我在Java端收到null。

采纳答案by CommonsWare

AFAIK, addJavascriptInterface()only works with primitive types and Strings, and so you cannot pass arbitrary Javascript objects.

AFAIK,addJavascriptInterface()仅适用于原始类型和字符串,因此您不能传递任意 Javascript 对象。

回答by e mail

I think you can also pass JSONObject and JSONArray. So not only primitive types, but also primitive types stored in a javascript array [0,1,2] or dictionary {one:1, two:2}.

我认为你也可以传递 JSONObject 和 JSONArray。所以不仅是原始类型,还有存储在 javascript 数组 [0,1,2] 或字典 {one:1, two:2} 中的原始类型。

I have NOT verified this in code, just read the docs. Might be using it soon.

我没有在代码中验证这一点,只是阅读文档。可能很快就会使用它。

回答by Derzu

I found a solution, using JSON. My Java method returns a JSONArray, on my javascript code I receive this and convert to a javascript vector using JSON.parse(). See the example:

我找到了一个解决方案,使用 JSON。我的 Java 方法返回一个 JSONArray,在我的 javascript 代码上,我收到它并使用 JSON.parse() 转换为 javascript 向量。看例子:

Java:

爪哇:

public class JavaScriptInterface {
Context mContext;
private static int ind=-1;
private static int [] val = { 25, 25, 50, 30, 40, 30, 30, 5, 9 };

public JavaScriptInterface(Context c) {
    mContext = c;
}

@JavascriptInterface
public JSONArray getChartData() {
    String texto = " [ {name: 'valor1', 2007: "+val[(++ind)%9]+"}, "+
                     " {name: 'valor2', 2007: "+val[(++ind)%9]+"}, "+
                     " {name: 'valor3', 2007: "+val[(++ind)%9]+"} ]"; 

    JSONArray jsonar=null;
    try {
        jsonar = new JSONArray(texto);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return jsonar;
}
}

Now the javascript code:

现在的javascript代码:

window.generateData = function() {
        /*var data = [ {name: 'valor1', 2007: 50},
                     {name: 'valor2', 2007: 20},
                     {name: 'valor3', 2007: 30} ];     */
        var data = JSON.parse( Android.getChartData() );
        return data;
    };

The commented code above show how it was when static, and now the data came from the Java code.

上面的注释代码显示了静态时的情况,现在数据来自 Java 代码。

It was testes on Android 2.1 and 3.2.

它是在 Android 2.1 和 3.2 上的睾丸。

回答by SergioM

You can't pass JSONObject or JSONArray, but you can send strings with that form and parse them to those types.

您不能传递 JSONObject 或 JSONArray,但您可以使用该形式发送字符串并将它们解析为这些类型。

Your option is to expose the method using strings and then you can use the JSONObject or JSONArray to parse the string and use it accordingly.

您的选择是使用字符串公开该方法,然后您可以使用 JSONObject 或 JSONArray 来解析字符串并相应地使用它。

Here is what I did.

这是我所做的。

@JavascriptInterface
public void passJSON(String array, String jsonObj) throws JSONException
{
    JSONArray myArray = new JSONArray(array);
    JSONObject myObj = new JSONObject(jsonObj);     
    ...

}

where array is '["string1","string2"]' and jsonObj is '{attr:1, attr2:"myName"}'

其中数组是 '["string1","string2"]' 和 jsonObj 是 '{attr:1, attr2:"myName"}'

回答by Tejasvi Hegde

This is how I am doing...

这就是我正在做的...

In Android...

在安卓...

@JavascriptInterface
public void getJSONTData(String jsonData) {
      try {
             JSONObject data = new JSONObject(jsonData); //Convert from string to object, can also use JSONArray
          } catch (Exception ex) {}
}

In JavaScript...

在 JavaScript 中...

var obj = { Name : 'Tejasvi', Age: 100};
var str = JSON.stringify(obj);
Android.getJSONTData(str);

As of now, I could not find any other proper way to pass the native JavaScript object directly to JavascriptInterface.

截至目前,我找不到任何其他正确的方法将本机 JavaScript 对象直接传递给 JavascriptInterface。

Calling Android.getJSONTData({ Name : 'Tejasvi', Age: 100})results in null(if parameter type is Object) or undefined(if parameter type is defined as String) in getJSONTData.

调用Android.getJSONTData({ Name : 'Tejasvi', Age: 100})导致null(如果参数类型为Object)或undefined(如果参数类型定义为String) in getJSONTData

回答by sel?uk do?an

I can run this feature

我可以运行这个功能

In Javascript :

在 JavaScript 中:

var data = {
            'username' : $('#username').val().trim(),
            'password' : $('#password').val().trim(),
            'dns' : $('#dns').val().trim()
        }
        var str = JSON.stringify(data);
        Native.getLoginService(str);

In Android :

在安卓中:

@JavascriptInterface
public void getLoginService(String jsonData){
    try{
        JSONObject data = new JSONObject(jsonData);
        String username = data.getString("username");
        String password = data.getString("password");
        String dns = data.getString("dns");

        Log.i("TAG",username + " - " + password + " - " + dns);

    }catch (Exception ex){
        Log.i("TAG","error : " + ex);
    }
}

Good luck with...

祝你好运...