針對 WebView 點擊行為進行最佳化

如果應用程式使用 WebView 顯示網頁內容,您可能需要考慮基於下列原因,最佳化點擊行為:

  • WebView 不支援分頁瀏覽。點選連結後,內容會在預設網路瀏覽器中開啟。
  • WebView 不支援自訂網址架構,如果點擊目的地是其他應用程式,廣告中可能會傳回這類架構。舉例來說,Google Play 點擊後到達網址可能會使用 market://

本指南提供建議步驟,協助您在保留網頁檢視內容的同時,最佳化行動版網頁檢視中的點擊行為。

必要條件

導入作業

請按照下列步驟,在WebView執行個體中最佳化點擊行為:

  1. 覆寫 WebViewClient 上的 shouldOverrideUrlLoading()。 當系統即將在目前的 WebView 中載入網址時,就會呼叫這個方法。

  2. 決定是否要覆寫點擊網址的行為。

    程式碼範例會檢查目前網域是否與目標網域不同。這只是一種方法,您使用的條件可能有所不同。

  3. 決定要在外部瀏覽器、Android Custom Tabs 或現有網頁檢視畫面中開啟網址。本指南說明如何啟動 Android 自訂分頁,開啟導向網站外部的網址。

程式碼範例

首先,請將 androidx.browser 依附元件新增至模組層級的 build.gradle 檔案 (通常為 app/build.gradle)。自訂分頁必須符合下列條件:

dependencies {
  implementation 'androidx.browser:browser:1.5.0'
}

下列程式碼片段說明如何實作 shouldOverrideUrlLoading()

Java

public class MainActivity extends AppCompatActivity {

  private WebView webView;

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // ... Register the WebView.

    webView = new WebView(this);
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webView.setWebViewClient(
        new WebViewClient() {
          // 1. Implement the web view click handler.
          @Override
          public boolean shouldOverrideUrlLoading(
              WebView view,
              WebResourceRequest request) {
            // 2. Determine whether to override the behavior of the URL.
            // If the target URL has no host and no scheme, return early.
            if (request.getUrl().getHost() == null && request.getUrl().getScheme() == null) {
              return false;
            }

            // Handle custom URL schemes such as market:// by attempting to
            // launch the corresponding application in a new intent.
            if (!request.getUrl().getScheme().equals("http")
                && !request.getUrl().getScheme().equals("https")) {
              Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
              // If the URL cannot be opened, return early.
              try {
                MainActivity.this.startActivity(intent);
              } catch (ActivityNotFoundException exception) {
                Log.d("TAG", "Failed to load URL with scheme:" + request.getUrl().getScheme());
              }
              return true;
            }

            String currentDomain;
            // If the current URL's host cannot be found, return early.
            try {
              currentDomain = new URI(view.getUrl()).toURL().getHost();
            } catch (URISyntaxException | MalformedURLException exception) {
              // Malformed URL.
              return false;
            }
            String targetDomain = request.getUrl().getHost();

            // If the current domain equals the target domain, the
            // assumption is the user is not navigating away from
            // the site. Reload the URL within the existing web view.
            if (currentDomain.equals(targetDomain)) {
              return false;
            }

            // 3. User is navigating away from the site, open the URL in
            // Custom Tabs to preserve the state of the web view.
            CustomTabsIntent intent = new CustomTabsIntent.Builder().build();
            intent.launchUrl(MainActivity.this, request.getUrl());
            return true;
          }
        });
  }
}

Kotlin

class MainActivity : AppCompatActivity() {

  private lateinit var webView: WebView

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    // ... Register the WebView.

    webView.webViewClient = object : WebViewClient() {
      // 1. Implement the web view click handler.
      override fun shouldOverrideUrlLoading(
          view: WebView?,
          request: WebResourceRequest?
      ): Boolean {
        // 2. Determine whether to override the behavior of the URL.
        // If the target URL has no host and no scheme, return early.
        if (request?.url?.host == null && request.url.scheme == null) {
          return false
        }
        val currentDomain = URI(view?.url).toURL().host

        // Handle custom URL schemes such as market:// by attempting to
        // launch the corresponding application in a new intent.
        if (!request.url.scheme.equals("http") &&
            !request.url.scheme.equals("https")) {
          val intent = Intent(Intent.ACTION_VIEW, request.url)
          // If the URL cannot be opened, return early.
          try {
            this@MainActivity.startActivity(intent)
          } catch (exception: ActivityNotFoundException) {
            Log.d("TAG", "Failed to load URL with scheme: ${request.url.scheme}")
          }
          return true
        }

        val targetDomain = request.url.host

        // If the current domain equals the target domain, the
        // assumption is the user is not navigating away from
        // the site. Reload the URL within the existing web view.
        if (currentDomain.equals(targetDomain)) {
          return false
        }

        // 3. User is navigating away from the site, open the URL in
        // Custom Tabs to preserve the state of the web view.
        val customTabsIntent = CustomTabsIntent.Builder().build()
        customTabsIntent.launchUrl(this@MainActivity, request.url)
        return true
      }
    }
  }
}

測試網頁瀏覽

如要測試網頁導覽變更,請載入

https://google.github.io/webview-ads/test/#click-behavior-tests

到網頁檢視畫面。點選各種類型的連結,即可查看連結在應用程式中的行為。

建議您確認以下事項:

  • 每個連結都會開啟預期網址。
  • 返回應用程式時,測試頁面的計數器不會重設為零,以驗證頁面狀態是否保留。