在 Android 開發中,我們使用 Webview 組件來加載 HTML5 頁面,WebView 默認提供了讓 Java 和 HTML5 頁面中的 JavaScript 腳本交互的能力。
Java 調用 JavaScript
Java 調用 JavaScript 中的函數,只需要執行以下代碼。
String html = " <!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
"<meta content=\"text/html;charset=UTF-8\"/>" +
"<script language=\"javascript\">" +
"function toast() {alert(\"test\");}" +
"</script>\n" +
"</head>\n" +
"</html>"
webView = findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {});
webView.loadData(html, "text/html", "UTF-8");
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
webView.loadUrl("javascript:toast()");
}
});
注意
- 如果不設置 WebChromeClient,Alert 無法彈出。
webView.setWebChromeClient(new WebChromeClient() {});
- 網頁的js代碼沒有加載,就調用了js方法,會報以下錯誤。
I/chromium: [INFO:CONSOLE(1)] "Uncaught ReferenceError: toast is not defined", source: (1)
所以在網頁加載完成之后調用js方法或者限制用戶在頁面加載完成之前不允許調用JS的事件。
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
webView.loadUrl("javascript:toast()");
}
});
JavaScript 調用 Java
方案一
WebView 提供了 WebSetting 工具類來實現讓 WebView 中的 JavaScript 腳本調用 Android 應用的 Java 方法。
- 調用與 WebView 關聯的 WebSettings 實例的 setJavaScriptEnabled 方法是否使用 JavsScript 的功能。
- 調用 WebView 的 addJavascriptInterface 方法將應用中的 Java 對象暴露給 JavaScript。
- 在 JavaScript 腳本中調用步驟二暴露出來的 Java 對象的方法。
public class WebViewActivity extends AppCompatActivity {
private WebView webView;
@SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
String html = " <!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
"<meta content=\"text/html;charset=UTF-8\"/>" +
"</head>\n" +
"<body style=\"background-color:black\">\n" +
"<input type=\"button\" value=\"顯示Toast\" onclick=\"injectedObject.showToast('test')\"/>" +
"</body>\n" +
"</html>";
webView = findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JsObject(), "injectedObject");
webView.loadData(html, "text/html", "UTF-8");
}
class JsObject {
@JavascriptInterface
public String toString() {
return "injectedObject";
}
@JavascriptInterface
public void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
}
}
這種方法在 Android 4.2 之前會存在安全隱患,會引起 WebView 遠程代碼執行漏洞。安卓4.2 開始,谷歌修復了這個漏洞,可以安全的使用上述的方法,唯一需要修改的是對暴露給 JavaScript 調用的方法增加 @JavascriptInterface。
方案二
如果需要支持 Android 4.2 之前的系統,需要用另外的方案規避這個問題,不再使用 addJavascriptInterface 這種方式。
JavaScript 有三種常用的消息提示框,分別是:彈出警告框 alert,彈出確認框 confirm 和彈出輸入框 prompt。對應到 Android 的 WebChromeClient 類,分別是以下三個方法。
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
return super.onJsAlert(view, url, message, result);
}
@Override
public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
return super.onJsConfirm(view, url, message, result);
}
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
return super.onJsPrompt(view, url, message, defaultValue, result);
}
這三個方法參數唯一的區別是返回給 JavaScript 的結果類型不一樣,前兩者是 JsResult,這個類中帶有一個布爾類型的結果值,而 onJsPrompt 是 JsPromptResult 類型,是 JsResult 的子類,帶有一個字符串類型的結果值。
public class JsResult {
/**
* Callback interface, implemented by the WebViewProvider implementation to receive
* notifications when the JavaScript result represented by a JsResult instance has
* @hide Only for use by WebViewProvider implementations
*/
@SystemApi
public interface ResultReceiver {
public void onJsResultComplete(JsResult result);
}
// This is the caller of the prompt and is the object that is waiting.
@UnsupportedAppUsage
private final ResultReceiver mReceiver;
// This is a basic result of a confirm or prompt dialog.
private boolean mResult;
/**
* Handle the result if the user cancelled the dialog.
*/
public final void cancel() {
mResult = false;
wakeUp();
}
/**
* Handle a confirmation response from the user.
*/
public final void confirm() {
mResult = true;
wakeUp();
}
/**
* @hide Only for use by WebViewProvider implementations
*/
@SystemApi
public JsResult(ResultReceiver receiver) {
mReceiver = receiver;
}
/**
* @hide Only for use by WebViewProvider implementations
*/
@SystemApi
public final boolean getResult() {
return mResult;
}
/* Notify the caller that the JsResult has completed */
private final void wakeUp() {
mReceiver.onJsResultComplete(this);
}
}
public class JsPromptResult extends JsResult {
// String result of the prompt
private String mStringResult;
/**
* Handle a confirmation response from the user.
*/
public void confirm(String result) {
mStringResult = result;
confirm();
}
/**
* @hide Only for use by WebViewProvider implementations
*/
@SystemApi
public JsPromptResult(ResultReceiver receiver) {
super(receiver);
}
/**
* @hide Only for use by WebViewProvider implementations
*/
@SystemApi
public String getStringResult() {
return mStringResult;
}
}
String 類型的結果值可以攜帶更多的信息,因此,選擇 onJsPrompt 方法作為解決方案,通過這個方法,我們能夠將 JavaScript 中將字符串信息(對應 onJsPrompt 入參中的 message)傳遞給 Java,而 Java 執行完成之后能夠把返回結果的字符串形式(對應 onJsPrompt 的返回值 mStringResult)傳遞給 JavaScript。基本思路如下。
- 首先需要基于這個字符串定義好通信的協議,可以是 JSON 格式,這個字符串中可能包含調用的類型 type,方法名 method,方法參數 args 等。
- 在 JavaScript 中封裝一個方法,它最終通過調用 prompt 方法實現將上面的文本協議信息傳遞給 Java 層 WebChromeClient 類的 onJsPrompt 方法,在這個方法中對協議信息進行解析,可以得到類型、方法名、參數等信息,通過 Java 的發射機制可以實現調用到對應的 Java 方法。
- 步驟二的 Java 方法執行完畢后,同理,需要定義好返回值的協議格式,并通過 JsPromptResult 返回給 JavaScript。
safe-java-js-webview-bridge 基于上訴方案已經實現了。