项目中遇到需要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.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

本文介绍WebView与Activity交互的两种方式:一是通过JavaScript调用Activity的方法,需启用JS并绑定JavaScriptInterface;二是Activity调用JavaScript,需在HTML中定义JS函数并通过WebView加载URL来触发。
1484

被折叠的 条评论
为什么被折叠?



