Tối ưu hoá hành vi nhấp chuột trong WebView

如果您的 Android 应用使用了 WebView 来展示 Web 内容,您可能希望 出于以下原因考虑优化点击行为:

  • WebView 不支持自定义网址架构 如果点击目标为单独的应用,则可能会在广告中返回。 例如,Google Play 点击后到达网址可能使用 market://

本指南介绍了针对移动设备优化点击行为的推荐步骤 同时保留网页视图内容。

前提条件

实现

请按照以下步骤优化 WebView 实例:

  1. 替换 shouldOverrideUrlLoading()WebViewClient上。 系统会在当前加载网址时调用此方法, WebView

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

    以下代码段会检查当前域名是否与 目标网域。这只是其中一种方法,因为您使用的条件可能有所不同。

  3. 决定是否在外部浏览器 (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, return early.
            if (request.getUrl().getHost() == 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, return early.
        request?.url?.host?.let { targetDomain ->
          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
          }

          // 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
        }
        return false
      }
    }
  }
}

测试网页导航

要测试页面导航更改,请加载

https://webview-api-for-ads-test.glitch.me#click-behavior-tests

进入网页视图点击各种不同的链接类型,查看它们是如何 行为

请检查以下几个方面:

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