最近做Android項目時需要進行webview與html頁面中的js進行交互,包括android調用js以及js調用android本地代碼,現將代碼整理記錄下。
整個佈局比較簡單,就是的一個TextView加一個WebView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
tools:context="com.example.demowebviewjs.MainActivity">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="調用js方法"
android:textSize="35sp" />
<WebView
android:id="@+id/wb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"></WebView>
</LinearLayout>
由於我們加載的網頁是在本地的,所以不需要任何權限,進行完控件的初始化後就加載頁面,並設置成支持js
WebView wb = (WebView) findViewById(R.id.wb);
//設置編碼
wb.getSettings().setDefaultTextEncodingName("utf-8");
//支持js
wb.getSettings().setJavaScriptEnabled(true);
//載入頁面
wb.loadUrl("file:///android_asset/test.html");
android調用網頁中的代碼比較簡單,只需要調用webview的loadUrl方法
wb.loadUrl("javascript:funFromjs()");
其中javascript是固定寫法,冒號後面跟上頁面中的方法名,如果方法中有參數的話只需要用單引號引用並且中間用逗號隔開,例如
wb.loadUrl("javascript:funFromjs('mUserName','mPsw')");
js調用安卓本地代碼的話webview需要調用addJavascriptInterface這個方法
//設置本地調用對象及其接口
wb.addJavascriptInterface(new Object() {
@JavascriptInterface //sdk17版本以上加上註解
public void funFromAndroid(String name) {
Toast.makeText(MainActivity.this, name,Toast.LENGTH_LONG).show();
}
public void fun(String name) {
Toast.makeText(MainActivity.this, "調用fun2:" + name, Toast.LENGTH_SHORT).show();
}
}, "android");
可以看到其實就是兩個參數,一個Object,一個String,其中Object中我們可以定義一些方法讓js調用,不過需要注意的是如果SDK版本號高於17的話,如果希望js可以調用,那麼需要在方法上加上@JavascriptInterface這個註解,後面的String就類似於對象名一樣,最後加上js的代碼
<!DOCTYPE html>
<html>
<head>
<meta chatset="utf-8" />
<title>This is a test</title>
</head>
<body>
<a>js中調用本地方法</a>
<script>
function funFromjs(){
document.getElementById("helloweb").innerHTML="HelloWebView,i'm from js";
}
var aTag = document.getElementsByTagName('a')[0];
aTag.addEventListener('click', function(){
//調用android本地方法
android.funFromAndroid("調用android本地方法funFromAndroid(String name)!!");
return false;
}, false);
</script>
<p></p>
<div id="helloweb">
</div>
</body>
</html>