Android中WebView与Javascript交互的问题

在Android开发中,使用WebView与Javascript交互,无非如下几个步骤:


1. 使能Javascript。
通过getSettings()获得WebSettings,然后用setJavaScriptEnabled()使能JavaScript


2. 创建Java对象
private Object javaEventObj = new Object() {
public void clickAction(int actionID) {
Log.d(LOG_TAG, "[javaEventObj:clickAction]" + actionID);
}
}


3. 绑定Java对象
调用WebView的 addJavascriptInterface()方法。


今天在开发时,仍旧遵照上面几个步骤,结果却不奏效。提示对象没有相应的方法。
于是查看addJavascriptInterface方法的说明,找到如下解释:


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


根据说明,添加注解:
private Object javaEventObj = new Object() {
@JavascriptInterface
public void clickAction(int actionID) {
Log.d(LOG_TAG, "[displayObj:clickAction]" + actionID);
}
}


重新运行,终于成功。


另外还要注意一下这个方法后面给出的提示:


IMPORTANT:
1. 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.
2. JavaScript interacts with Java object on a private, background thread of this WebView. Care is therefore required to maintain thread safety.
3. The Java object's fields are not accessible.


英文比较简单,就不翻译了。

你可能感兴趣的:(Android开发)