1. 程式人生 > >如何設定WebView支援js的Alert,Confirm,Prompt函式的彈出提示框.

如何設定WebView支援js的Alert,Confirm,Prompt函式的彈出提示框.

預設情況下,Android WebView是不支援js的Alert(),Confirm(),Prompt()函式的彈出提示框的.即使設定了setJavaScriptEnabled(true);也是沒用的.那麼,如何才能讓WebView可以支援js的這3個函式呢.可以通過設定WebChromeClient物件來完成.WebChromeClient主要輔助WebView處理Javascript的對話方塊、網站圖示、網站title、載入進度等等.

這裡主要重寫WebChromeClient的3個方法:

onJsAlert  :警告框(WebView上alert無效,需要定製WebChromeClient處理彈出)

onJsPrompt : 提示框.

onJsConfirm : 確定框.

效果圖分別為:

1.Alert


2.Prompt


3.Confirm


先來看看js的頁面程式碼:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Document</title>
    <script type="text/javascript">
       function call(){
            var value = document.getElementById("input").value;
            alert(value);
       }
       //警告
       function onAlert(){
            alert("This is a alert sample from html");
       }
       //確定
       function onConfirm(){
          var b = confirm("are you sure to login?");
          alert("your choice is "+b);
       }
       //提示
       function onPrompt(){
           var b = prompt("please input your password","aaa");
           alert("your input is "+b);
       }
    </script>

</head>
<body>
    <input type="text" id="input" value="default"/>
    <button onclick=call()>點我彈出Alert</button></br>
    <input type="button" value="alert" onclick="onAlert()"/></br>
    <input type="button" value="confirm" onclick="onConfirm()"/></br>
    <input type="button" value="prompt" onclick="onPrompt()"/></br>
</body>

</html>
Android程式碼:
package com.example.chenys.webviewdemo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.TextView;

/**
 * Created by mChenys on 2015/11/19.
 */
public class TestAlertActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WebView webView = new WebView(this);
        setContentView(webView);
        webView.requestFocus();
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);//啟用支援js
        //設定響應js 的Alert()函式
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                AlertDialog.Builder b = new AlertDialog.Builder(TestAlertActivity.this);
                b.setTitle("Alert");
                b.setMessage(message);
                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                });
                b.setCancelable(false);
                b.create().show();
                return true;
            }
            //設定響應js 的Confirm()函式
            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                AlertDialog.Builder b = new AlertDialog.Builder(TestAlertActivity.this);
                b.setTitle("Confirm");
                b.setMessage(message);
                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                });
                b.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.cancel();
                    }
                });
                b.create().show();
                return true;
            }
            //設定響應js 的Prompt()函式
            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) {
                final View v = View.inflate(TestAlertActivity.this, R.layout.prompt_dialog, null);
                ((TextView) v.findViewById(R.id.prompt_message_text)).setText(message);
                ((EditText) v.findViewById(R.id.prompt_input_field)).setText(defaultValue);
                AlertDialog.Builder b = new AlertDialog.Builder(TestAlertActivity.this);
                b.setTitle("Prompt");
                b.setView(v);
                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String value = ((EditText) v.findViewById(R.id.prompt_input_field)).getText().toString();
                        result.confirm(value);
                    }
                });
                b.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.cancel();
                    }
                });
                b.create().show();
                return true;
            }
        });
        webView.loadUrl("file:///android_asset/index3.html");
    }
}

有2個需要注意的:

1.重寫onJsPrompt 方法,需要我們自定一個提示的佈局檔案,如下:prompt_dialog.xml

就是一個提示的TextView和輸入文字的EditTex而已.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/prompt_message_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/prompt_input_field"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minWidth="250dp"
        android:selectAllOnFocus="true"
        android:scrollHorizontally="true"/>
</LinearLayout>

2.WebView需要支援js的話,要記得加啟用js的支援.
 WebSettings settings = webView.getSettings();
 settings.setJavaScriptEnabled(true);