android--WebView使用addJavascriptInterface在sdk 17的問題

當調用WebView 的addJavascriptInterface時,使用android:targetSdkVersion="10"時是沒有問題的,可以觸發事件,可是畢竟使用版本時通常都使用最新的,我在開發時爲了追求新,而後使用了android:targetSdkVersion="17"的屬性,開始使用時並無什麼問題,大多數手機是能夠使用的,好比中興的N986,小米的MIMU4.1的系統是沒有問題的,系統爲2.3的幾個機型也沒看出問題,後來三星Note3上出問題啦,調用不了這個事件,我也糾結了半天,後來在網上查找緣由,是去年android的漏洞所致,javascript

因此修改方法有兩個:html

1,修改android:targetSdkVersion="10",這個只能爲一時的解決方案,java

2. 查找官方文件:說在17以上須要添加一個接口JavascriptInterface才能用,後來仔細看了官方的Demo才找到,就是藍色加粗部分。若是這個問題您也遇到過,但願能幫助你,謝謝android

官方給的說明:web

public void addJavascriptInterface (Object object, String name)

Added in API level 1app

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.ide

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

 class JsObject {    @JavascriptInterface    public String toString() { return "injectedObject"; } } webView.addJavascriptInterface(new JsObject(), "injectedObject"); webView.loadData("", "text/html", null); webView.loadUrl("javascript:alert(injectedObject.toString())");

IMPORTANT:this

  • 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.spa

  • 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
object the Java object to inject into this WebView's JavaScript context. Null values are ignored.
name the name used to expose the object in JavaScript
相關文章
相關標籤/搜索