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