优化 WebView 点击行为

如果您的应用利用 WebView 显示 Web 内容,您可能需要考虑优化点击行为,原因如下:

  • WebView 不支持自定义网址方案,如果点击目标是另一个应用,则可能会在广告中返回该方案。 例如,Google Play 点击后到达网址可能会使用 market://

本指南提供了建议的步骤,可在保留 WebView 内容的同时优化移动 WebView 中的点击行为。

前提条件

实现

请按照以下步骤优化 WebView 实例中的点击行为:

  1. 覆盖 WebViewClient 上的 shouldOverrideUrlLoading()。 当网址即将在当前 WebView 中加载时,系统会调用此方法。

  2. 确定是否替换点击网址的行为。

    代码示例用于检查当前网域是否与目标网域不同。这只是一种方法,您使用的条件可能会有所不同。

  3. 决定是在外部浏览器、Android 自定义标签页中还是在现有 WebView 中打开网址。本指南介绍了如何通过启动 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

到您的 WebView 中。点击每种不同的链接类型,了解它们在应用中的行为。

请检查以下几个方面:

  • 每个链接都会打开预期的网址。
  • 返回应用时,测试页面的计数器不会重置为零,以验证页面状态是否已保留。