您的位置:首页 > 移动开发 > Android开发

Android中 Webview中js与Activity的交互

2014-05-24 19:18 274 查看
项目中遇到需要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="确定"  onclick="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.csdn.net/sy_bz/article/details/6874571

@2:http://blog.csdn.net/wangtingshuai/article/details/8631835

@3:http://blog.csdn.net/leehong2005/article/details/11808557

@4:http://www.incoding.org/admin/archives/727.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: