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

Nếu ứng dụng của bạn sử dụng WebView để hiển thị nội dung web, bạn nên cân nhắc việc tối ưu hoá hành vi nhấp vì những lý do sau:

  • WebView không hỗ trợ tính năng duyệt theo thẻ. Khi bạn nhấp vào một đường liên kết, nội dung sẽ mở trong trình duyệt web mặc định.
  • WebView không hỗ trợ lược đồ URL tuỳ chỉnh có thể được trả về trong quảng cáo nếu đích đến của lượt nhấp là một ứng dụng riêng biệt. Ví dụ: URL của trang đích khi nhấp trên Google Play có thể sử dụng market://.

Hướng dẫn này cung cấp các bước đề xuất để tối ưu hoá hành vi nhấp trong chế độ xem web trên thiết bị di động, đồng thời vẫn giữ nguyên nội dung chế độ xem web.

Điều kiện tiên quyết

Triển khai

Hãy làm theo các bước sau để tối ưu hoá hành vi nhấp trong thực thể WebView:

  1. Ghi đè shouldOverrideUrlLoading() trên WebViewClient. Phương thức này được gọi khi một URL sắp được tải trong WebView hiện tại.

  2. Xác định xem có ghi đè hành vi của URL lượt nhấp hay không.

    Ví dụ về mã kiểm tra xem miền hiện tại có khác với miền mục tiêu hay không. Đây chỉ là một phương pháp vì tiêu chí bạn sử dụng có thể khác nhau.

  3. Quyết định xem có mở URL trong trình duyệt bên ngoài, Thẻ tuỳ chỉnh của Android hay trong chế độ xem web hiện có hay không. Hướng dẫn này cho biết cách mở các URL rời khỏi trang web bằng cách chạy Thẻ tuỳ chỉnh Android.

Ví dụ về mã

Trước tiên, hãy thêm phần phụ thuộc androidx.browser vào tệp build.gradle cấp mô-đun, thường là app/build.gradle. Đây là yêu cầu bắt buộc đối với Thẻ tuỳ chỉnh:

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

Đoạn mã sau đây cho thấy cách triển khai 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
      }
    }
  }
}

Kiểm tra tính năng điều hướng trang

Để kiểm thử các thay đổi về điều hướng trang, hãy tải

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

vào chế độ xem web. Nhấp vào từng loại đường liên kết để xem cách các đường liên kết đó hoạt động trong ứng dụng của bạn.

Dưới đây là một số điểm cần kiểm tra:

  • Mỗi đường liên kết sẽ mở ra URL dự kiến.
  • Khi quay lại ứng dụng, bộ đếm của trang kiểm thử không đặt lại về 0 để xác thực trạng thái trang đã được giữ nguyên.