Android原生与JavaScript交互中传递数据的类型问题

今天在与H5前端交互的过程中,有按照设计文档预留JavaScriptInterface对象给js调用,然而H5反馈无法取得数据。

     public JsonObject  getAndroidDeviceInfo() {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("systemId", DeviceUtils.getSystemId(CApplication.getInstance()));
            return jsonObject;
        }

后经过检查发现在JavaScriptInterface的方法中返回类型是对象,而webview中的js是无法访问Android原生中的对象地址的,所以获取数据为空,后转换成Json格式的数据串就行了。

     public String  getAndroidDeviceInfo() {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("systemId", DeviceUtils.getSystemId(CApplication.getInstance()));
            return jsonObject.toString();
        }

   然后以为事情就此结束,然后H5方面还是反应可以获取到对象了,但是无法调用对象.属性名获取字段值。为了节省时间,自己也做了个静态Html页面放在了AndroidStudio工程中,测试下Js调用原生返回值时的各种场景。

   H5调用时获取到的是Json格式的字符串,还不是能直接使用的对象,需要将其转换成Object类型。将获取的字符串解析为对象,才能调用objectName.propertyName获取字段信息

 function show(arg) {
            alert(JSON.parse(android.ShowToast()).systemId)
        }

在Webview.addJavaScriptInterface()方法中,其实有备注,我们需要注意下线程和数据域访问问题

https://developer.android.google.cn/reference/kotlin/android/webkit/WebView.html#addjavascriptinterface
JavaScript interacts with Java object on a private, background thread of this WebView. Care is therefore required to maintain thread safety.

Because the object is exposed to all the frames, any frame could obtain the object name and call methods on it. There is no way to tell the calling frame's origin from the app side, so the app must not assume that the caller is trustworthy unless the app can guarantee that no third party content is ever loaded into the WebView even inside an iframe.

The Java object's fields are not accessible.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值