WebView的使用總結

WebView是android常見的一個組件,隨著混合開發的發展,越來越多的公司使用原生和h5共同開發。所以使用WebView的頻率越來越高了,所以想做次總結

<a name="t0" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>WebView的常見用法

<a name="t1" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>最簡單的用法

<a name="t2" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>loadUrl

loadUrl(String url);

加載一個網頁,其中注意的是

1. 需要加入聯網權限,

2. 還有網址必須完整即以http://或者ftp://等協議開頭,不能省略!不然將加載不出來,

3. assert中的html文件。前綴換成file:///android_asset/

4. 加載sd卡中的html文件,前綴換成content://

<uses-permission android:name="android.permission.INTERNET" /> 

<a name="t3" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>loadData

public void loadData(String data, String mimeType, String encoding)

加載代碼塊。其中對于data可以采用encode一下再加載,速度快點

<a name="t4" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>loadDataWithBaseURL

public void loadDataWithBaseURL(String baseUrl, String data,String mimeType, String encoding, String historyUrl)

相對于loadData,其實就是一個相對路徑和絕對路徑的問題,loadData要求必須是絕對路徑,而loadDataWithBaseURL則可以是相對路徑。historyUrl可以為null。


<a name="t5" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>WebSettings的常見配置

如果我們需要設置WebView的屬性,是通過WebView.getSettings()獲取取設置WebView的WebSettings對象,然后調用WebSettings中的方法來實現的配置一些屬性,來幫我們實現一些常見的基本操作。比如字體大小,支持縮放等

//---------------------------------------------------
// 縮放
// 1 設置支持縮放,默認true
setSupportZoom(boolean support)

// 2 設置顯示縮放的組件 默認true
setDisplayZoomControls(boolean enabled)  

// 3 設置是否使用縮放的內置組件  默認false
setBuiltInZoomControls(boolean enabled) 
//--------------------------------------------------

//--------------------------------------------------
// 1 設置media 手勢播放media
setMediaPlaybackRequiresUserGesture(boolean require)
//--------------------------------------------------

//--------------------------------------------------
//寬度
// 1 設置概述模式瀏覽界面,當頁面寬度超過WebView顯示寬度時,縮小頁面適應WebView。默認false 
setLoadWithOverviewMode(boolean overview)    

// 2 設置支持ViewPort的meta tag屬性,如果頁面有ViewPort meta tag 指定的寬度,則使用meta tag指定的值,否則默認使用寬屏的視圖窗口 
setUseWideViewPort(boolean use)  
//--------------------------------------------------

//--------------------------------------------------
// 字體和大小
// 1 設置頁面文字縮放百分比,默認100% 
setTextZoom(int textZoom)  

// 2 設置最小字體,默認8\. 取值區間[1-72],超過范圍,使用其上限值。 
setMinimumFontSize(int size)

//3 設置最小邏輯字體,默認8\. 取值區間[1-72],超過范圍,使用其上限值。 
setMinimumLogicalFontSize(int size)  

//4 設置默認字體大小,默認16,取值區間[1-72],超過范圍,使用其上限值。 
setDefaultFontSize(int size)

//5 設置默認填充字體大小,默認16,取值區間[1-72],超過范圍,使用其上限值
setDefaultFixedFontSize(int size)  

//6 設置默認字體大小 SMALLEST is 50% SMALLER is 75% NORMAL is 100% LARGER is 150% LARGEST is 200%
setTextSize(WebSettings.TextSize t)

//7 設置標準的字體族,默認”sans-serif”。
setStandardFontFamily(String font) 

//8 設置混合字體族。默認”monospace”
setFixedFontFamily(String font) 

//9 設置SansSerif字體族。默認”sans-serif”
setSansSerifFontFamily(String font)

//10 設置SerifFont字體族,默認”sans-serif” 
setSerifFontFamily(String font) 

//11 設置CursiveFont字體族,默認”cursive” 
setCursiveFontFamily(String font)  

//12 設置FantasyFont字體族,默認”fantasy” 
setFantasyFontFamily(String font)  

//13 設置頁面的編碼格式,默認UTF-8
setDefaultTextEncodingName(String encoding)
//--------------------------------------------------------

//--------------------------------------------------------
//加載圖片
//1 設置是否加載圖片資源 包括嵌入的本地圖片資源和網絡圖片。 默認true 
setLoadsImagesAutomatically(boolean flag)  

//2 是否加載網絡圖片資源 默認true
setBlockNetworkImage(boolean flag) 

//3 設置是否加載網絡資源。注意如果值從true切換為false后,WebView不會自動加載,除非調用WebView#reload()
setBlockNetworkLoads(boolean flag) 
//-------------------------------------------------------

//--------------------------------------------------------
//訪問
//1 設置允許訪問WebView內部文件,默認true 
setAllowFileAccess(boolean allow)  

//2 設置允許獲取WebView的內容URL ,可以讓WebView訪問ContentPrivider存儲的內容。 默認true
setAllowContentAccess(boolean allow) 

//3 設置加載不安全資源的WebView加載行為,MIXED_CONTENT_ALWAYS_ALLOW和MIXED_CONTENT_NEVER_ALLOW 
setMixedContentMode(int mode)  
//--------------------------------------------------------

//緩存
//1 是否保存表單數據,默認false 
//setSaveFormData(boolean save) 

//2 是否允許數據庫存儲
setDatabaseEnabled(boolean flag)

//3 設置存儲定位數據庫的位置,考慮到位置權限和持久化Cache緩存
setGeolocationDatabasePath(String databasePath) 

//4 是否允許Cache,默認false
setAppCacheEnabled(boolean flag)

//5 設置Cache API緩存路徑。
setAppCachePath(String appCachePath)

//6 是否存儲頁面DOM結構,默認false
setDomStorageEnabled(boolean flag) 

//7 基于WebView導航的類型使用緩存 LOAD_DEFAULT 默認加載方式 LOAD_CACHE_ELSE_NETWORK 按網絡情況使用緩存 LOAD_NO_CACHE 不使用緩存 LOAD_CACHE_ONLY 只使用緩存 
setCacheMode(int mode) 

//--------------------------------------------------------

//--------------------------------------------------------
//js
//1 設置是否允許執行JS
setJavaScriptEnabled(boolean flag)  

//2 是否允許Js訪問任何來源的內容。包括訪問file scheme的URLs
setAllowUniversalAccessFromFileURLs(boolean flag)

//3 是否允許Js訪問其他file scheme的URLs
setAllowFileAccessFromFileURLs(boolean flag)  

//4 是否允許JS自動打開窗口。默認false 
setJavaScriptCanOpenWindowsAutomatically(boolean flag)
//--------------------------------------------------------

// ------------------------------------------------------
// 其它
//1 設置WebView代理,默認使用默認值
setUserAgentString(String ua) 

//是否允許定位,默認true
setGeolocationEnabled(boolean flag)

//是否支持多窗口,如果設置為true 
setSupportMultipleWindows(boolean support)

<a name="t6" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>JS和本地的互調

<a name="t7" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>JS調用Android

主要代碼:

mWebView = (WebView) findViewById(R.id.webview);  

WebSettings webSettings = mWebView.getSettings();  
webSettings.setJavaScriptEnabled(true);  
mWebView.addJavascriptInterface(mJavaInterface, "rrtoyewx");

其中

public void addJavascriptInterface(Object obj, String interfaceName)

第一個參數obj對象中實現JS調用android的實現的方法,第二個參數interfaceName是向WebView注入一個interfaceName的對象,這個對象綁定的是obj對象,即js的中調用方法的對象。

舉個例子

js調用android的sendMessage的方法,并傳遞一個String的參數。

js代碼

<html lang="en">  
    <head>  
        <meta charset="UTF-8">  
        <title>Title</title>  
        <h1>你好</h1>  
        <input type="button" value="js調native" onclick="ok()">  
    </head>  
    <body>  
        <script type="text/javascript">  
        function ok() {  
            rrtoyewx.sendMessage("我調用了android的中代碼");  
        }  
        </script>  
    </body>  
</html>  

android的代碼

mWebView = (WebView) findViewById(R.id.webview);  

WebSettings webSettings = mWebView.getSettings();  
webSettings.setJavaScriptEnabled(true);  
mWebView.addJavascriptInterface(mJavaInterface, "rrtoyewx");

JavaInterface的代碼

public class JavaInterface{
    @JavascriptInterface 
    public void sendMessage(String message){
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show(); 
    }
}

其中js調用java的代碼會造成Android WebView的Js對象注入漏洞,會造成一些安全性的問題,關于這個的解決方法就是也有別人分析出并解決了

Android WebView的Js對象注入漏洞解決方案,其中對4.2以上采用@JavascriptInterface的注釋,而對于4.2以下的系統

1. 不使用addJavascriptInterface的方法。

2. 在WebChromeClient的方法中的回調方法中,去解析相應的參數,方法名,然后通過反射去相應本地方法。

3. 如果存在返回值,則通過的load的方式,會調用的相應的方法。

<a name="t8" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>Android 調用js的方法

loadUrl();

直接通過loadUrl()的方式去加載js的方法。

舉個例子

Android 調用js的alert的方法

Js

<html lang="en">  
    <head>  
        <meta charset="UTF-8">  
        <title>Title</title>  
        <h1 id="h">Rrtoyewx</h1>  
        <input type="button" value="js調native" onclick="ok()">  
    </head>  
    <body>  
        <script type="text/javascript">  
            function showAlert(i)  
            {  
                ....
            }  
        </script>  
    </body>  
</html> 

Android 的代碼

mWebView.loadUrl("javascript:showAlert(“java調用了js的方法”)");  

如果js的方法存在返回值,一種方式需要用js調用java的方式將返回值作為返回。而4.4之后,還有另一種方式,通過evaluateJavascript的方法去調用js的方法,并在valueCallBack的回調方法“onReceiveValue(String value)”的方法回調。

public void evaluateJavascript("methodName",valueCallBack)
mWebView.evaluateJavascript("getGreetings()", new ValueCallback() {  
       @Override  
       public void onReceiveValue(String value) {  
           Log.d("Rrtoyewx", value);  
       }  
   }); 

注意,回調方法在主線程,第二,返回值只接受string的


<a name="t9" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>WebViewClient的回調方法

<a name="t10" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>onPageStarted

public void onPageStarted(WebView view, String url, Bitmap favicon)   

當前頁面開始加載時調用,我們可以在其中做一些準備的工作,比如加載processbar

<a name="t11" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>onPageFinished

public void onPageFinished(WebView view, String url)  

當前頁面的加載完成時調用,我們可以在其中釋放一個資源,和關閉一些東西

<a name="t12" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>shouldOverrideUrlLoading

public boolean shouldOverrideUrlLoading(WebView view, String url)

函數會在加載其他的鏈接時回調,表示webview是否屏蔽的這個鏈接,默認返回false,如果返回true則表示不會加載這個url了。我們可以在其中屏蔽一些操作。

<a name="t13" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>onReceivedError

public void onReceivedError(WebView view, int errorCode,String description, String failingUrl)  

參數的說明:WebView view:當前的WebView實例,int errorCode:錯誤碼,String description:錯誤描述,String failingUrl:當前出錯的URL。一般加載本地的404界面的,即出現一個錯誤提示。

<a name="t14" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>onReceivedSslError

public void onReceivedSslError(WebView view, SslErrorHandler handler,SslError error) 

HTTPS協議是通過SSL來通信的,所以當使用HTTPS通信的網址(以https://開頭的網站)出現錯誤時,就會回調的該方法,參數說明

WebView view:當前的WebView實例,SslErrorHandler handler:SslErrorHandler.proceed()和SslErrorHandler.cancel(),SslErrorHandler.proceed()表示忽略錯誤繼續加載,SslErrorHandler.cancel()表示取消加載。在onReceivedSslError的默認實現中是使用的SslErrorHandler.cancel()來取消加載。SslError error:當前的的錯誤對象,SslError包含了當前SSL錯誤的基本所有信息。

注意

1 onReceivedSslError回調,不一定會回調onReceivedError的方法。

2 加載默認的onReceivedSslError的會出現的白屏。

3 可以忽略這個錯誤繼續加載的

<a name="t15" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>shouldInterceptRequest

public WebResourceResponse shouldInterceptRequest(WebView view,  
        String url) ;

當頁面中許多的資源文件,每請求一個資源文件,都會回調這個方法,這個不主線程調用。所以我們可以在請求資源的時候,在這里屏蔽一些操作

<a name="t16" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>onLoadResource

public void onLoadResource(WebView view, String url

請求資源文件的時候調用,

<a name="t17" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>onScaleChanged

public void onScaleChanged(WebView view, float oldScale, float newScale)  

webView的發生縮放改變的時候調用

<a name="t18" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>shouldOverrideKeyEvent

public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event)  

屏蔽一個按鍵的操作,返回false,則不屏蔽,交給webview處理,true反之

<a name="t19" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>onFormResubmission

onFormResubmission(WebView view, Message dontResend, Message resend)  

設置是否重發數據,post的請求的時候,默認不重新發送

<a name="t20" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>doUpdateVisitedHistory

doUpdateVisitedHistory(WebView view, String url, boolean isReload) 

通知主機程序更新訪問的鏈接

<a name="t21" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>onUnhandledInputEvent

onUnhandledInputEvent(WebView view, InputEvent event) 

讓主程序處理WebView未處理的Input Event。

<a name="t22" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>onReceivedLoginRequest

onReceivedLoginRequest(WebView view, String realm, String account, String args)

自動登錄請求的回調方法


<a name="t23" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>WebChromeClient的事件

<a name="t24" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>onJsAlert

public boolean onJsAlert(WebView view, String url, String message,JsResult result)

網頁調用alert的時候調用

<a name="t25" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>onJsConfirm(),返回值代表是否消費, JsResult 的cancle的方法和con

public boolean onJsConfirm(WebView view, String url, String message,JsResult result)

網頁調用confirm的時候調用,返回值代表是否消費,

<a name="t26" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>onJsPrompt

public boolean onJsPrompt(WebView view, String url, String message,String defaultValue, JsPromptResult result) 

網頁調用prompt的時候調用,返回值代表是否消費,

<a name="t27" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>onConsoleMessage

public boolean onConsoleMessage(ConsoleMessage consoleMessage)

打印console的消息的時候,常用來監視js代碼的錯誤

<a name="t28" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>onProgressChanged

 public void onProgressChanged(WebView view, int newProgress)

加載頁面的進度的改變的時候,

<a name="t29" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>onReceivedTitle

public void onReceivedTitle(WebView view, String title)

頁面的title的發生變化時候的回調

<a name="t30" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>onReceivedIcon

public void onReceivedIcon(WebView view, Bitmap icon)

接受到新的icon的回調方法

<a name="t31" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>onReceivedTouchIconUrl

public void  onReceivedTouchIconUrl(WebView view, String url, boolean precomposed)

頁面的按下圖標的icon的url

<a name="t32" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>getVisitedHistory

public void getVisitedHistory(ValueCallback callback)

獲取訪問頁面的訪問歷史

<a name="t33" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>onShowFileChooser

public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback,FileChooserParams fileChooserParams)

試圖打開文件的瀏覽器的回調方法,其中fileChooserParams對象包含的許多的信息。比如打開文件的mimeType,mode等


from:http://blog.csdn.net/zhi184816/article/details/51832711

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容