WebView使用中js调用java代码时targetSdkVersion大于17时,无法调用成功

       开发过程中需要使用webview加载一个网络图片并在点击图片时有相应的动作,由于webview截获了一切动作事件,使用js调用java本地代码的方式来完成需求,在使用时,发现在use-sdk中配置android:targetSdkVersion大于17时,js不能调用到java代码,

    修改方法有两个:

       1.修改android:targetSdkVersion="10",这个只能为一时的解决方案,

       2. 查找官方文件:说在17以上需要添加一个接口JavascriptInterface才能用,即在js调用的java代码上方加上JavascriptInterface的注解,同时,在混淆代码时,注意不要混淆JavascriptInterface的注解,否则也会出现js不能调用java代码的情况发生。(-keepattributes *Annotation*)

 

官方给的说明:

public void addJavascriptInterface (Object object, String name)

Added in API level 1

Injects the supplied Java object into this WebView. The object is injected into the JavaScript context of the main frame, using the supplied name. This allows the Java object's methods to be accessed from JavaScript. For applications targeted to API level JELLY_BEAN_MR1 and above, only public methods that are annotated with JavascriptInterface can be accessed from JavaScript. For applications targeted to API level JELLY_BEAN or below, all public methods (including the inherited ones) can be accessed, see the important security note below for implications.

Note that injected objects will not appear in JavaScript until the page is next (re)loaded. For example:

?
1
2
3
4
5
6
7
class JsObject {
   <strong> @JavascriptInterface </strong>
   public String toString() { return "injectedObject" ; }
}
webView.addJavascriptInterface( new JsObject(), "injectedObject" );
webView.loadData( "" , "text/html" , null );
webView.loadUrl( "javascript:alert(injectedObject.toString())" );

IMPORTANT:

  • This method can be used to allow JavaScript to control the host application. This is a powerful feature, but also presents a security risk for applications targeted to API level JELLY_BEAN or below, because JavaScript could use reflection to access an injected object's public fields. Use of this method in a WebView containing untrusted content could allow an attacker to manipulate the host application in unintended ways, executing Java code with the permissions of the host application. Use extreme care when using this method in a WebView which could contain untrusted content.
  • JavaScript interacts with Java object on a private, background thread of this WebView. Care is therefore required to maintain thread safety.
  • The Java object's fields are not accessible.

    Parameters
    objectthe Java object to inject into this WebView's JavaScript context. Null values are ignored.
    namethe name used to expose the object in JavaScript

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值