如果要顯示JavaScript alert
函數的消息框,則不強制使用WebChromeClient
。您可以在您的JavaScript代碼和客戶端Android代碼之間創建接口。
在下面的例子中,JavaScript代碼可以調用在Android代碼的方法來顯示Dialog
,代替使用JavaScript的alert()
功能。我發現這是顯示警報的最方便和廣泛支持的方式。
包括在你的Android應用程序的類:
文件:WebAppInterface.java
import android.content.Context;
import android.webkit.JavascriptInterface;
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a Message box from the web page */
@JavascriptInterface
public void androidAlert(String message) {
DialogBox dbx = new DialogBox();
dbx.dialogBox(message, "I get it", "",mContext);
}
}
文件:DialogBox.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
public class DialogBox {
public boolean dialogBox(String msg, String okButton, String cancelButton, final Context activity) {
Dialog v = null;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
alertDialogBuilder.setMessage(msg);
if (okButton != "") {
alertDialogBuilder.setPositiveButton(okButton,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) { /**/ }
});
}
if (cancelButton != "") {
alertDialogBuilder.setNegativeButton(cancelButton,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) { /**/ }
});
}
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
return true;
}
}
接下來,綁定WebAppInterface
級的JavaScript,在你的WebView
與addJavascriptInterface()
運行,並命名接口Android
:
WebView mWebView = (WebView) findViewById(R.id.webview);
mWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
這將創建一個名爲Android
對JavaScript的運行WebView
的接口。此時,您的Web應用程序可以訪問WebAppInterface
類。下面是一些HTML和JavaScript,當用戶點擊一個按鈕,創建使用新界面,一個消息框:
<input type="button" value="Alert!" onClick="javascript:Android.androidAlert('It works!');" />
在點擊按鈕時,Android
接口用於調用WebAppInterface.androidAlert()
方法。
有點警告:使用addJavascriptInterface()
允許JavaScript來控制你的Android應用程序。這可能是非常有用的功能或危險安全問題。因此,除非您編寫出現在WebView
中的所有HTML和JavaScript,否則不應使用addJavascriptInterface()
。
http://stackoverflow.com/questions/8634319/how-to-set-different -title-for-alert-dialog-when-webview-page-is-loaded – Raghunandan 2013-05-11 05:39:51
@Ganesh:你想顯示android原生AlertDialog(http://developer.android.com/reference/android/app/AlertDialog.html) ? – 2013-05-11 05:41:37