WebView是android常見的一個組件闰挡,隨著混合開發(fā)的發(fā)展鹃觉,越來越多的公司使用原生和h5共同開發(fā)酷鸦。所以使用WebView的頻率越來越高了荆责,所以想做次總結(jié)
<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);
加載一個網(wǎng)頁滥比,其中注意的是
1. 需要加入聯(lián)網(wǎng)權(quán)限,
2. 還有網(wǎng)址必須完整即以http://或者ftp://等協(xié)議開頭,不能省略草巡!不然將加載不出來守呜,
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一下再加載,速度快點(diǎn)
<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,其實(shí)就是一個相對路徑和絕對路徑的問題郁竟,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的常見配置
如果我們需要設(shè)置WebView的屬性蓖议,是通過WebView.getSettings()獲取取設(shè)置WebView的WebSettings對象,然后調(diào)用WebSettings中的方法來實(shí)現(xiàn)的配置一些屬性,來幫我們實(shí)現(xiàn)一些常見的基本操作讥蟆。比如字體大小勒虾,支持縮放等
//---------------------------------------------------
// 縮放
// 1 設(shè)置支持縮放,默認(rèn)true
setSupportZoom(boolean support)
// 2 設(shè)置顯示縮放的組件 默認(rèn)true
setDisplayZoomControls(boolean enabled)
// 3 設(shè)置是否使用縮放的內(nèi)置組件 默認(rèn)false
setBuiltInZoomControls(boolean enabled)
//--------------------------------------------------
//--------------------------------------------------
// 1 設(shè)置media 手勢播放media
setMediaPlaybackRequiresUserGesture(boolean require)
//--------------------------------------------------
//--------------------------------------------------
//寬度
// 1 設(shè)置概述模式瀏覽界面瘸彤,當(dāng)頁面寬度超過WebView顯示寬度時(shí)修然,縮小頁面適應(yīng)WebView。默認(rèn)false
setLoadWithOverviewMode(boolean overview)
// 2 設(shè)置支持ViewPort的meta tag屬性质况,如果頁面有ViewPort meta tag 指定的寬度愕宋,則使用meta tag指定的值,否則默認(rèn)使用寬屏的視圖窗口
setUseWideViewPort(boolean use)
//--------------------------------------------------
//--------------------------------------------------
// 字體和大小
// 1 設(shè)置頁面文字縮放百分比结榄,默認(rèn)100%
setTextZoom(int textZoom)
// 2 設(shè)置最小字體中贝,默認(rèn)8\. 取值區(qū)間[1-72],超過范圍臼朗,使用其上限值邻寿。
setMinimumFontSize(int size)
//3 設(shè)置最小邏輯字體蝎土,默認(rèn)8\. 取值區(qū)間[1-72],超過范圍绣否,使用其上限值瘟则。
setMinimumLogicalFontSize(int size)
//4 設(shè)置默認(rèn)字體大小,默認(rèn)16枝秤,取值區(qū)間[1-72]醋拧,超過范圍,使用其上限值淀弹。
setDefaultFontSize(int size)
//5 設(shè)置默認(rèn)填充字體大小丹壕,默認(rèn)16,取值區(qū)間[1-72]薇溃,超過范圍菌赖,使用其上限值
setDefaultFixedFontSize(int size)
//6 設(shè)置默認(rèn)字體大小 SMALLEST is 50% SMALLER is 75% NORMAL is 100% LARGER is 150% LARGEST is 200%
setTextSize(WebSettings.TextSize t)
//7 設(shè)置標(biāo)準(zhǔn)的字體族,默認(rèn)”sans-serif”沐序。
setStandardFontFamily(String font)
//8 設(shè)置混合字體族琉用。默認(rèn)”monospace”
setFixedFontFamily(String font)
//9 設(shè)置SansSerif字體族。默認(rèn)”sans-serif”
setSansSerifFontFamily(String font)
//10 設(shè)置SerifFont字體族策幼,默認(rèn)”sans-serif”
setSerifFontFamily(String font)
//11 設(shè)置CursiveFont字體族邑时,默認(rèn)”cursive”
setCursiveFontFamily(String font)
//12 設(shè)置FantasyFont字體族,默認(rèn)”fantasy”
setFantasyFontFamily(String font)
//13 設(shè)置頁面的編碼格式特姐,默認(rèn)UTF-8
setDefaultTextEncodingName(String encoding)
//--------------------------------------------------------
//--------------------------------------------------------
//加載圖片
//1 設(shè)置是否加載圖片資源 包括嵌入的本地圖片資源和網(wǎng)絡(luò)圖片晶丘。 默認(rèn)true
setLoadsImagesAutomatically(boolean flag)
//2 是否加載網(wǎng)絡(luò)圖片資源 默認(rèn)true
setBlockNetworkImage(boolean flag)
//3 設(shè)置是否加載網(wǎng)絡(luò)資源。注意如果值從true切換為false后唐含,WebView不會自動加載,除非調(diào)用WebView#reload()
setBlockNetworkLoads(boolean flag)
//-------------------------------------------------------
//--------------------------------------------------------
//訪問
//1 設(shè)置允許訪問WebView內(nèi)部文件浅浮,默認(rèn)true
setAllowFileAccess(boolean allow)
//2 設(shè)置允許獲取WebView的內(nèi)容URL ,可以讓W(xué)ebView訪問ContentPrivider存儲的內(nèi)容捷枯。 默認(rèn)true
setAllowContentAccess(boolean allow)
//3 設(shè)置加載不安全資源的WebView加載行為,MIXED_CONTENT_ALWAYS_ALLOW和MIXED_CONTENT_NEVER_ALLOW
setMixedContentMode(int mode)
//--------------------------------------------------------
//緩存
//1 是否保存表單數(shù)據(jù)滚秩,默認(rèn)false
//setSaveFormData(boolean save)
//2 是否允許數(shù)據(jù)庫存儲
setDatabaseEnabled(boolean flag)
//3 設(shè)置存儲定位數(shù)據(jù)庫的位置,考慮到位置權(quán)限和持久化Cache緩存
setGeolocationDatabasePath(String databasePath)
//4 是否允許Cache淮捆,默認(rèn)false
setAppCacheEnabled(boolean flag)
//5 設(shè)置Cache API緩存路徑郁油。
setAppCachePath(String appCachePath)
//6 是否存儲頁面DOM結(jié)構(gòu),默認(rèn)false
setDomStorageEnabled(boolean flag)
//7 基于WebView導(dǎo)航的類型使用緩存 LOAD_DEFAULT 默認(rèn)加載方式 LOAD_CACHE_ELSE_NETWORK 按網(wǎng)絡(luò)情況使用緩存 LOAD_NO_CACHE 不使用緩存 LOAD_CACHE_ONLY 只使用緩存
setCacheMode(int mode)
//--------------------------------------------------------
//--------------------------------------------------------
//js
//1 設(shè)置是否允許執(zhí)行JS
setJavaScriptEnabled(boolean flag)
//2 是否允許Js訪問任何來源的內(nèi)容争剿。包括訪問file scheme的URLs
setAllowUniversalAccessFromFileURLs(boolean flag)
//3 是否允許Js訪問其他file scheme的URLs
setAllowFileAccessFromFileURLs(boolean flag)
//4 是否允許JS自動打開窗口已艰。默認(rèn)false
setJavaScriptCanOpenWindowsAutomatically(boolean flag)
//--------------------------------------------------------
// ------------------------------------------------------
// 其它
//1 設(shè)置WebView代理痊末,默認(rèn)使用默認(rèn)值
setUserAgentString(String ua)
//是否允許定位蚕苇,默認(rèn)true
setGeolocationEnabled(boolean flag)
//是否支持多窗口,如果設(shè)置為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和本地的互調(diào)
<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調(diào)用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)
第一個參數(shù)obj對象中實(shí)現(xiàn)JS調(diào)用android的實(shí)現(xiàn)的方法凿叠,第二個參數(shù)interfaceName是向WebView注入一個interfaceName的對象涩笤,這個對象綁定的是obj對象嚼吞,即js的中調(diào)用方法的對象。
舉個例子
js調(diào)用android的sendMessage的方法蹬碧,并傳遞一個String的參數(shù)舱禽。
js代碼
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<h1>你好</h1>
<input type="button" value="js調(diào)native" onclick="ok()">
</head>
<body>
<script type="text/javascript">
function ok() {
rrtoyewx.sendMessage("我調(diào)用了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調(diào)用java的代碼會造成Android WebView的Js對象注入漏洞,會造成一些安全性的問題恩沽,關(guān)于這個的解決方法就是也有別人分析出并解決了
Android WebView的Js對象注入漏洞解決方案誊稚,其中對4.2以上采用@JavascriptInterface的注釋,而對于4.2以下的系統(tǒng)
1. 不使用addJavascriptInterface的方法罗心。
2. 在WebChromeClient的方法中的回調(diào)方法中里伯,去解析相應(yīng)的參數(shù),方法名渤闷,然后通過反射去相應(yīng)本地方法疾瓮。
3. 如果存在返回值,則通過的load的方式飒箭,會調(diào)用的相應(yīng)的方法狼电。
<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 調(diào)用js的方法
loadUrl();
直接通過loadUrl()的方式去加載js的方法。
舉個例子
Android 調(diào)用js的alert的方法
Js
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<h1 id="h">Rrtoyewx</h1>
<input type="button" value="js調(diào)native" onclick="ok()">
</head>
<body>
<script type="text/javascript">
function showAlert(i)
{
....
}
</script>
</body>
</html>
Android 的代碼
mWebView.loadUrl("javascript:showAlert(“java調(diào)用了js的方法”)");
如果js的方法存在返回值弦蹂,一種方式需要用js調(diào)用java的方式將返回值作為返回肩碟。而4.4之后,還有另一種方式凸椿,通過evaluateJavascript的方法去調(diào)用js的方法腾务,并在valueCallBack的回調(diào)方法“onReceiveValue(String value)”的方法回調(diào)。
public void evaluateJavascript("methodName",valueCallBack)
mWebView.evaluateJavascript("getGreetings()", new ValueCallback() {
@Override
public void onReceiveValue(String value) {
Log.d("Rrtoyewx", value);
}
});
注意削饵,回調(diào)方法在主線程岩瘦,第二,返回值只接受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的回調(diào)方法
<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)
當(dāng)前頁面開始加載時(shí)調(diào)用窿撬,我們可以在其中做一些準(zhǔn)備的工作启昧,比如加載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)
當(dāng)前頁面的加載完成時(shí)調(diào)用,我們可以在其中釋放一個資源,和關(guān)閉一些東西
<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)
函數(shù)會在加載其他的鏈接時(shí)回調(diào)劈伴,表示webview是否屏蔽的這個鏈接密末,默認(rèn)返回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)
參數(shù)的說明:WebView view:當(dāng)前的WebView實(shí)例,int errorCode:錯誤碼追城,String description:錯誤描述刹碾,String failingUrl:當(dāng)前出錯的URL。一般加載本地的404界面的座柱,即出現(xiàn)一個錯誤提示迷帜。
<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協(xié)議是通過SSL來通信的物舒,所以當(dāng)使用HTTPS通信的網(wǎng)址(以https://開頭的網(wǎng)站)出現(xiàn)錯誤時(shí),就會回調(diào)的該方法,參數(shù)說明
WebView view:當(dāng)前的WebView實(shí)例戏锹,SslErrorHandler handler:SslErrorHandler.proceed()和SslErrorHandler.cancel()冠胯,SslErrorHandler.proceed()表示忽略錯誤繼續(xù)加載,SslErrorHandler.cancel()表示取消加載锦针。在onReceivedSslError的默認(rèn)實(shí)現(xiàn)中是使用的SslErrorHandler.cancel()來取消加載荠察。SslError error:當(dāng)前的的錯誤對象,SslError包含了當(dāng)前SSL錯誤的基本所有信息奈搜。
注意
1 onReceivedSslError回調(diào)割粮,不一定會回調(diào)onReceivedError的方法。
2 加載默認(rèn)的onReceivedSslError的會出現(xiàn)的白屏媚污。
3 可以忽略這個錯誤繼續(xù)加載的
<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) ;
當(dāng)頁面中許多的資源文件舀瓢,每請求一個資源文件,都會回調(diào)這個方法耗美,這個不主線程調(diào)用京髓。所以我們可以在請求資源的時(shí)候,在這里屏蔽一些操作
<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
請求資源文件的時(shí)候調(diào)用商架,
<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的發(fā)生縮放改變的時(shí)候調(diào)用
<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)
設(shè)置是否重發(fā)數(shù)據(jù),post的請求的時(shí)候赶袄,默認(rèn)不重新發(fā)送
<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)
通知主機(jī)程序更新訪問的鏈接
<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)
自動登錄請求的回調(diào)方法
<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)
網(wǎng)頁調(diào)用alert的時(shí)候調(diào)用
<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(),返回值代表是否消費(fèi)饿肺, JsResult 的cancle的方法和con
public boolean onJsConfirm(WebView view, String url, String message,JsResult result)
網(wǎng)頁調(diào)用confirm的時(shí)候調(diào)用蒋困,返回值代表是否消費(fèi),
<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)
網(wǎng)頁調(diào)用prompt的時(shí)候調(diào)用敬辣,返回值代表是否消費(fèi)雪标,
<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的消息的時(shí)候,常用來監(jiān)視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)
加載頁面的進(jìn)度的改變的時(shí)候溉跃,
<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的發(fā)生變化時(shí)候的回調(diào)
<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的回調(diào)方法
<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)
頁面的按下圖標(biāo)的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)
試圖打開文件的瀏覽器的回調(diào)方法,其中fileChooserParams對象包含的許多的信息村刨。比如打開文件的mimeType,mode等
from:http://blog.csdn.net/zhi184816/article/details/51832711