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

Nếu ứng dụng Android của bạn sử dụng WebView để hiển thị nội dung trên web, bạn nên để xem xét tối ưu hóa 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 bạn nhấp vào một đường liên kết, nội dung sẽ xuất hiện trong trình duyệt web mặc định.
  • WebView không hỗ trợ lược đồ URL tùy 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 trên thiết bị di động chế độ xem web mà 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 chuột trong WebView thực thể:

  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.

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

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

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

Ví dụ về mã

Trước tiên, hãy thêm phần phụ thuộc androidx.browser vào 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 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 điều hướng trang

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

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

vào chế độ xem trên 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 dự kiến.
  • Khi quay lại ứng dụng, bộ đếm của trang thử nghiệm không đặt lại về 0 thành xác thực trạng thái trang được giữ nguyên.