android 中webView与Activity之间的交互

本文介绍了如何在Android项目中实现webview与activity之间的交互,包括webview中使用js调用activity方法,activity调用js,以及注意事项。特别强调了在Android4.2及以上版本中调用方法前需加注解@JavascriptInterface。

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

项目中遇到需要webview与activity的交互,于是去baidu上google了一下。发现了如下方法:

一、webview中运用js调用activity方法

1、启用js

WebView.getSettings().setJavaScriptEnabled(true);


2、绑定javascriptInterface

WebView.addJavascriptInterface(this, "wv"); 

@JavascriptInterface
public void getJS(String s) {//TODO 这里做相应的逻辑操作。}
 

或者

WebView.addJavascriptInterface(new Object(){
		@JavascriptInterface  
		public void getJS(String s) {
				//TODO 这里做相应的逻辑操作。
		}
}, url);


 
 
两个参数:一个是Object的方法,一个是js调用时候的别名; 

3、html中调用

<input name="submit" type="submit" value="确定"  οnclick="return f2()" />

<script type="text/javascript">
	function f2(){
		return window.wv.getJS("cc");
	}
</script>

二、activity调用js

1、html中加入js

<script type="text/javascript">  
function java2js(){  
     document.getElementById("id").innerHTML +=     
         "<br\>java调用了js函数";  
}  
  
function java2jswithargs(arg){  
     document.getElementById("id").innerHTML +=     
         ("<br\>"+arg);  
}  
  
</script>  


2、webview启用js

WebView.getSettings().setJavaScriptEnabled(true);

3、webview加载

// 无参数调用  
WebView.loadUrl("javascript:java2js()");  
// 传递参数调用  
WebView.loadUrl("javascript:java2jswithargs(" + "'hello world'" + ")"); 


三、对于android 4.2或以上,js调用activity时需要在函数前加上

@JavascriptInterface

原因如下:

From the Android 4.2 documentation:

   Caution: If you've set your targetSdkVersion to 17 or higher, you must add the @JavascriptInterface annotation to any method that you want available your web page code (the method must also be public). If you do not provide the annotation, then the method will not accessible by your web page when running on Android 4.2 or higher.


四、后来又看到一篇文章说在android4.2以前的webview的js存在注入漏洞@3,这就是android4.2修改该方法申明的原因了。


特别鸣谢:

@1:http://blog.youkuaiyun.com/sy_bz/article/details/6874571

@2:http://blog.youkuaiyun.com/wangtingshuai/article/details/8631835

@3:http://blog.youkuaiyun.com/leehong2005/article/details/11808557

@4:http://www.incoding.org/admin/archives/727.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值