Android中WebView与Javascript交互的问题

本文介绍在Android开发中如何正确配置WebView以实现与JavaScript的交互,包括使能JavaScript、创建及绑定Java对象,并解决API级别不同导致的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值