WebViewClient shouldOverrideUrlLoading 常見錯誤用法


需求描述

在使用 WebView 的項目中,一個常見的需求是將頁面內的鏈接跳轉限制在 WebView 內,而不是使用外部瀏覽器打開,但 WebView 的默認行為是將鏈接點擊事件作為 Intent 發送給系統,由系統決定如何處理(通常的行為是使用瀏覽器打開或是彈出瀏覽器選擇對話框),那么如何實現期望的效果呢?

實現方案

文章關於用WebView或手機瀏覽器打開連接問題給出了一種使用 WebViewClient#shouldOverrideUrlLoading方法的方案可以達到效果,但其使用該方法的方式是錯誤的,且被廣泛傳播。因此,有必要在此澄清一下。

WebView#shouldOverrideUrlLoading 的 api doc 如下

public boolean shouldOverrideUrlLoading (WebView view, String url) Added in API level 1 
Give the host application a chance to take over the control when a > new url is about to be loaded in the current WebView.
If WebViewClient is not provided, by default WebView will ask Activity Manager to choose the proper handler for the url.
If WebViewClient is provided, return true means the host application handles the url, while return false means the current WebView handles the url. This method is not called for requests using the POST "method".
Parameters view The WebView that is initiating the callback. url The url to be loaded.

Returns True if the host application wants to leave the current WebView and handle the url itself, otherwise return false.

翻譯一下,三種情況:

  1. 若沒有設置 WebViewClient 則在點擊鏈接之后由系統處理該 url,通常是使用瀏覽器打開或彈出瀏覽器選擇對話框。
  2. 若設置 WebViewClient 且該方法返回 true ,則說明由應用的代碼處理該 url,WebView 不處理。
  3. 若設置 WebViewClient 且該方法返回 false,則說明由 WebView 處理該 url,即用 WebView 加載該 url。

因此,開篇的需求使用如下方法即可實現:

設置 WebViewClient 且在其 shouldOverrideUrlLoading 方法返回 false

示例程序見 WebViewClientTest


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM