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

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

  • WebView không hỗ trợ duyệt web bằng thẻ. Khi nhấp vào một đường liên kết, nội dung sẽ mở ra 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à về 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 đưa ra các bước được đề xuất để tối ưu hoá hành vi nhấp chuột trong chế độ xem web dành cho thiết bị di động trong khi vẫn duy trì nội dung chế độ xem trên 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 chuột trong bản saoWebView của bạn:

  1. Ghi đè shouldOverrideUrlLoading() trên WebViewClient. Phương thức này được gọi khi 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 nhấp chuột hay không.

    Đoạn mã dưới đây sẽ 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 tiếp cận vì các tiêu chí mà bạn sử dụng có thể khác nhau.

  3. Quyết định mở URL trong trình duyệt bên ngoài, Thẻ tuỳ chỉnh trên Android, hay trong chế độ xem web hiện có. 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 của 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 biết 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 URL(view.getUrl()).getHost();
            } catch (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 = URL(view?.url).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 thử thao tác điều hướng trên trang

Để kiểm tra các thay đổi về cách điều hướng trên 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 liên kết khác nhau để xem cách chúng 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ở URL mà bạn muốn.
  • Khi quay lại ứng dụng, bộ đếm của trang thử nghiệm sẽ không đặt lại về 0 để xác thực trạng thái trang được giữ nguyên.