A few days ago, I encountered a BUG in the project:
We used WebView In the Android project to open an online banking payment url. When we click "pay", they will pop up an inquiry box using js on the webpage. The js Code is as follows:
- function testConfirm() {
- if(confirm("pay or not?")) {
- alert("yes! i do");
- }
- else
- {
- alert("no!!!");
- }
- }
If I didn't process the js event in webView, the process could not be correctly executed.
After checking the api, the solution is as follows:
First, set the webView attributes:
- mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
Second, set WebChromeClient:
- MWebView. setWebChromeClient (new WebChromeClient (){
-
- @ Override
- Public boolean onJsAlert (WebView view, String url, String message,
- Final JsResult result ){
- AlertDialog. Builder builder = new AlertDialog. Builder (mContext );
- Builder. setMessage (message)
- . SetNeutralButton ("OK", new OnClickListener (){
- @ Override
- Public void onClick (DialogInterface arg0, int arg1 ){
- Arg0.dismiss ();
- }
- }). Show ();
- Result. cancel ();
- Return true;
- }
-
- @ Override
- Public boolean onJsConfirm (WebView view, String url,
- String message, final JsResult result ){
- // TODO Auto-generated method stub
- Log. I (TAG, "onJsConfirm" + "," + "url:" + url );
-
- DialogUtils. dialogBuilder (mContext, "tip", message,
- New DialogCallBack (){
-
- @ Override
- Public void onCompate (){
- Log. I (TAG, "onJsConfirm, onCompate ");
- Result. confirm ();
- }
-
- @ Override
- Public void onCancel (){
- Log. I (TAG, "onJsConfirm, onCancel ");
- Result. cancel ();
- }
- });
- Return true;
- }
- });
In this way, the alert () and confirm () Events of javascript can be captured in webView.
Url for test: http://liucundong.sinaapp.com/testWebView.php