天天看點

Android WebView判定網頁加載的錯誤

一 前言

在WebView加載網頁的過程中,有時會頁面加載不出來的情況,如下:

Android WebView判定網頁加載的錯誤

那麼如何知道網頁加載錯誤了呢?

二 解決方法

webview.webViewClient = object : WebViewClient() {
    override fun onPageFinished(view: WebView?, url: String?) {
        super.onPageFinished(view, url)
        Log.d(TAG, "onPageFinished: ")
    }

    override fun onReceivedError(
        view: WebView?,
        request: WebResourceRequest?,
        error: WebResourceError?
    ) {
        super.onReceivedError(view, request, error)
        Log.d(TAG, "onReceivedError: request= " + request.json())
        Log.d(TAG, "onReceivedError: error= " + error.json())
    }
}
webview.loadUrl("https://www.baidu.com/")
           

request輸出:

{“a”:{“a”:“https://www.baidu.com/”,“b”:true,“c”:false,“d”:false,“e”:“GET”,“f”:{“User-Agent”:“Mozilla/5.0 (Linux; Android 11; sdk_gphone_x86_arm Build/RSR1.200819.001.A1; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/83.0.4103.106 Mobile Safari/537.36”,“Accept”:“text/html,application/xhtml+xml,application/xml;q\u003d0.9,image/webp,image/apng,/;q\u003d0.8,application/signed-exchange;v\u003db3;q\u003d0.9”,“Upgrade-Insecure-Requests”:“1”}}}

error輸出:

{“a”:{“a”:-1,“b”:“net::ERR_CACHE_MISS”}}
/**
* 需要注意的是:與老版本不同,新版本已經針對所有的資源加載錯誤都會回調*(iframe, image, etc.), 不僅僅是加載的首頁面
 */
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
    if (request.isForMainFrame()) {
        onReceivedError(view,
                error.getErrorCode(), error.getDescription().toString(),
                request.getUrl().toString());
    }
}
           

是以,通過以上監聽,即可知道對應的錯誤内容,進而做相應的業務處理。

三 常見的錯誤案例分析

1.錯誤:ERR_UNKNOWN_URL_SCHEME

複現條件:打開百度新聞資訊網頁,并點選評論

Android WebView判定網頁加載的錯誤
載體 現象
App内置WebView 報錯:ERR_UNKNOWN_URL_SCHEME
UC、華為浏覽器 停留在目前頁面狀态
Chrome浏覽器 跳轉到百度APP内部打開

來看一下頁面加載shouldOverrideUrlLoading 中回調request輸出:

{“a”:{“a”:“baiduboxapp://v1/easybrowse/hybrid?upgrade\u003d1\u0026type\u003dhybrid\u0026tpl_id\u003dlanding_app.html\u0026newbrowser\u003d1\u0026style\u003d%7B%22toolbaricons%22%3A%7B%22tids%22%3A%5B%224%22%2C%221%22%2C%222%22%2C%223%22%5D%2C%22menumode%22%3A%222%22%2C%22actionBarConfig%22%3A%7B%22extCase%22%3A%220%22%7D%7D%7D\u0026slog\u003d%7B%22from%22%3A%22feed%22%7D\u0026context\u003d%7B%22nid%22%3A%22news_9777178803801641010%22%7D\u0026ch_url\u003dhttps%3A%2F%2Fmbd.baidu.com%2Fnewspage%2Fdata%2Flandingreact%3FpageType%3D2%26nid%3Dnews_9777178803801641010%26uk%3D%26sourceFrom%3DlandingShare\u0026commentInfo\u003d%7B%22topic_id%22%3A1066000039731532%2C%22opentype%22%3A2%7D\u0026logargs\u003d%7B%22source%22%3A%221020283l%22%2C%22channel%22%3A%221020283m%22%7D\u0026needlog\u003d1”,“b”:false,“c”:true,“d”:false,“e”:“GET”,“f”:{“Accept”:“text/html,application/xhtml+xml,application/xml;q\u003d0.9,image/avif,image/webp,image/apng,/;q\u003d0.8,application/signed-exchange;v\u003db3;q\u003d0.9”,“Referer”:“https://mbd.baidu.com/newspage/data/landingpage?s_type\u003dnews\u0026dsp\u003dwise\u0026context\u003d%7B%22nid%22%3A%22news_9777178803801641010%22%7D\u0026pageType\u003d1\u0026n_type\u003d1\u0026p_from\u003d-1\u0026innerIframe\u003d1”,“Upgrade-Insecure-Requests”:“1”}}}

可以發現協定不是http類開頭,而是百度自己定義的"baiduboxapp"。是以,不做處理,當然是識别不了的。

2.實作UC、華為浏覽器處理的效果——>無視

webview.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                Log.d(TAG, "shouldOverrideUrlLoading: ${request.json()}")
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    Log.d(TAG, "shouldOverrideUrlLoading: url->${request?.url}")
                    if (view != null && request?.url?.toString() != null) {
                        if (request.url.toString().startsWith("http")) {
                            view.loadUrl(request.url.toString())
                        }
                return true
            }

           

3.如何實作Chrome浏覽器處理的效果——>能跳轉

假定這是百度适配Chrome的效果,而不是Chrome主動去适配百度的代碼頁面,那麼說明用戶端的WebView也是能做到這樣效果的。

基于此,我們來urldecode一下協定内容來看看request有什麼特殊:

baiduboxapp://v1/easybrowse/hybrid?upgrade=1&type=hybrid&tpl_id=landing_app.html&newbrowser=1&style={“toolbaricons”:{“tids”:[“4”,“1”,“2”,“3”],“menumode”:“2”,“actionBarConfig”:{“extCase”:“0”}}}&slog={“from”:“feed”}&context={“nid”:“news_9777178803801641010”}&ch_url=https://mbd.baidu.com/newspage/data/landingreact?pageType=2&nid=news_9777178803801641010&uk=&sourceFrom=landingShare&commentInfo={“topic_id”:1066000039731532,“opentype”:2}&logargs={“source”:“1020283l”,“channel”:“1020283m”}&needlog=1

整體來看,仍舊是符合URI規則的。這樣的話就可以考慮使用Intent處理的方式了。

webview.webViewClient = object : WebViewClient() {
    override fun shouldOverrideUrlLoading(
        view: WebView?,
        request: WebResourceRequest?
    ): Boolean {
        Log.d(TAG, "shouldOverrideUrlLoading: ${request.json()}")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Log.d(TAG, "shouldOverrideUrlLoading: url->${request?.url}")
            if (view != null && request?.url?.toString() != null) {
                if (request.url.toString().startsWith("http")) {
                    view.loadUrl(request.url.toString())
                } else {
                    try {
                        Log.d(TAG, "shouldOverrideUrlLoading: 開始跳轉")
                        startActivity(Intent(Intent.ACTION_VIEW, request.url))
                    } catch (e: Exception) {
                        Log.d(TAG, "shouldOverrideUrlLoading: ${e.json()}")
                    }
                }
            }
        }

        return true
    }
           

運作檢視效果如下:

Android WebView判定網頁加載的錯誤

從結果來看,能跳轉至百度的App,假定成立。

也就是針對非http協定位址的情況,可使用 startActivity(Intent(Intent.ACTION_VIEW, request.url)) 之類來進行協定内容處理。

四 總結

最後,根據自家業務來定協定并處理,畢竟不是誰都願意自家使用者跳出自家App的。

Android WebView判定網頁加載的錯誤