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

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

  • WKWebView không hỗ trợ tính năng duyệt web theo thẻ. Theo mặc định, các lượt nhấp vào quảng cáo cố gắng mở một thẻ mới sẽ không làm gì cả.

  • Lượt nhấp vào quảng cáo mở trong cùng một thẻ sẽ tải lại trang. Bạn có thể muốn buộc các lượt nhấp vào quảng cáo mở bên ngoài WKWebView, ví dụ: nếu bạn lưu trữ trò chơi H5 và muốn duy trì trạng thái của từng trò chơi.

  • Tính năng Tự động điền không hỗ trợ thông tin thẻ tín dụng trong WKWebView. Điều này có thể dẫn đến việc nhà quảng cáo có ít lượt chuyển đổi thương mại điện tử hơn, ảnh hưởng tiêu cực đến hoạt động kiếm tiền của nội dung trên web.

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

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

Triển khai

Đường liên kết của quảng cáo có thể đặt thuộc tính đích href thành _blank, _top, _self hoặc _parent. Đường liên kết quảng cáo cũng có thể chứa các hàm JavaScript, chẳng hạn như window.open(url, "_blank").

Bảng sau đây mô tả cách từng đường liên kết này hoạt động trong chế độ xem web.

href thuộc tính mục tiêu Hành vi nhấp vào WKWebView mặc định
target="_blank" Đường liên kết không được xử lý bởi chế độ xem web.
target="_top" Tải lại đường liên kết trong chế độ xem web hiện có.
target="_self" Tải lại đường liên kết trong chế độ xem web hiện có.
target="_parent" Tải lại đường liên kết trong chế độ xem web hiện có.
Hàm JavaScript Hành vi nhấp vào WKWebView mặc định
window.open(url, "_blank") Đường liên kết không được xử lý bởi chế độ xem web.

Hãy làm theo các bước sau để tối ưu hoá hành vi nhấp vào trong phiên bản WKWebView của bạn:

  1. Đặt WKUIDelegate trên thực thể WKWebView của bạn.

  2. Đặt WKNavigationDelegate trên thực thể WKWebView của bạn.

  3. Xác định xem có nên tối ưu hoá hành vi của URL nhấp chuột hay không.

    • Kiểm tra xem thuộc tính navigationType trên đối tượng WKNavigationAction có phải là loại lượt nhấp mà bạn muốn tối ưu hoá hay không. Ví dụ về mã kiểm tra .linkActivated chỉ áp dụng cho lượt nhấp vào một đường liên kết có thuộc tính href.

    • Kiểm tra thuộc tính targetFrame trên đối tượng WKNavigationAction. Nếu trả về nil, tức là đích đến của thao tác điều hướng là một cửa sổ mới. Vì WKWebView không thể xử lý lượt nhấp đó, nên bạn phải xử lý các lượt nhấp này theo cách thủ công.

  4. Quyết định xem có nên mở URL trong trình duyệt bên ngoài, SFSafariViewController hay chế độ xem web hiện có hay không. Đoạn mã này cho biết cách mở các URL điều hướng ra khỏi trang web bằng cách trình bày một SFSafariViewController.

Ví dụ về mã

Đoạn mã sau đây cho biết cách tối ưu hoá hành vi nhấp vào khung hiển thị web. Ví dụ: hàm này 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 cách tiếp cận vì tiêu chí bạn sử dụng có thể khác.

Swift

import GoogleMobileAds
import SafariServices
import WebKit

class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {

  override func viewDidLoad() {
    super.viewDidLoad()

    // ... Register the WKWebView.

    // 1. Set the WKUIDelegate on your WKWebView instance.
    webView.uiDelegate = self;
    // 2. Set the WKNavigationDelegate on your WKWebView instance.
    webView.navigationDelegate = self
  }

  // Implement the WKUIDelegate method.
  func webView(
      _ webView: WKWebView,
      createWebViewWith configuration: WKWebViewConfiguration,
      for navigationAction: WKNavigationAction,
      windowFeatures: WKWindowFeatures) -> WKWebView? {
    // 3. Determine whether to optimize the behavior of the click URL.
    if didHandleClickBehavior(
        currentURL: webView.url,
        navigationAction: navigationAction) {
      print("URL opened in SFSafariViewController.")
    }

    return nil
  }

  // Implement the WKNavigationDelegate method.
  func webView(
      _ webView: WKWebView,
      decidePolicyFor navigationAction: WKNavigationAction,
      decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
  {
    // 3. Determine whether to optimize the behavior of the click URL.
    if didHandleClickBehavior(
        currentURL: webView.url,
        navigationAction: navigationAction) {
      return decisionHandler(.cancel)
    }

    decisionHandler(.allow)
  }

  // Implement a helper method to handle click behavior.
  func didHandleClickBehavior(
      currentURL: URL,
      navigationAction: WKNavigationAction) -> Bool {
    guard let targetURL = navigationAction.request.url else {
      return false
    }

    // Handle custom URL schemes such as itms-apps:// by attempting to
    // launch the corresponding application.
    if navigationAction.navigationType == .linkActivated {
      if let scheme = targetURL.scheme, !["http", "https"].contains(scheme) {
        UIApplication.shared.open(targetURL, options: [:], completionHandler: nil)
        return true
      }
    }

    guard let currentDomain = currentURL.host,
      let targetDomain = targetURL.host else {
      return false
    }

    // Check if the navigationType is a link with an href attribute or
    // if the target of the navigation is a new window.
    if (navigationAction.navigationType == .linkActivated ||
      navigationAction.targetFrame == nil) &&
      // If the current domain does not equal the target domain,
      // the assumption is the user is navigating away from the site.
      currentDomain != targetDomain {
      // 4. Open the URL in a SFSafariViewController.
      let safariViewController = SFSafariViewController(url: targetURL)
      present(safariViewController, animated: true)
      return true
    }

    return false
  }
}

Objective-C

@import GoogleMobileAds;
@import SafariServices;
@import WebKit;

@interface ViewController () <WKNavigationDelegate, WKUIDelegate>

@property(nonatomic, strong) WKWebView *webView;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  // ... Register the WKWebView.

  // 1. Set the WKUIDelegate on your WKWebView instance.
  self.webView.uiDelegate = self;
  // 2. Set the WKNavigationDelegate on your WKWebView instance.
  self.webView.navigationDelegate = self;
}

// Implement the WKUIDelegate method.
- (WKWebView *)webView:(WKWebView *)webView
  createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration
             forNavigationAction:(WKNavigationAction *)navigationAction
                  windowFeatures:(WKWindowFeatures *)windowFeatures {
  // 3. Determine whether to optimize the behavior of the click URL.
  if ([self didHandleClickBehaviorForCurrentURL: webView.URL
      navigationAction: navigationAction]) {
    NSLog(@"URL opened in SFSafariViewController.");
  }

  return nil;
}

// Implement the WKNavigationDelegate method.
- (void)webView:(WKWebView *)webView
    decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
                    decisionHandler:
                        (void (^)(WKNavigationActionPolicy))decisionHandler {
  // 3. Determine whether to optimize the behavior of the click URL.
  if ([self didHandleClickBehaviorForCurrentURL: webView.URL
      navigationAction: navigationAction]) {
    decisionHandler(WKNavigationActionPolicyCancel);
    return;
  }

  decisionHandler(WKNavigationActionPolicyAllow);
}

// Implement a helper method to handle click behavior.
- (BOOL)didHandleClickBehaviorForCurrentURL:(NSURL *)currentURL
                    navigationAction:(WKNavigationAction *)navigationAction {
  NSURL *targetURL = navigationAction.request.URL;

  // Handle custom URL schemes such as itms-apps:// by attempting to
  // launch the corresponding application.
  if (navigationAction.navigationType == WKNavigationTypeLinkActivated) {
    NSString *scheme = targetURL.scheme;
    if (![scheme isEqualToString:@"http"] && ![scheme isEqualToString:@"https"]) {
      [UIApplication.sharedApplication openURL:targetURL options:@{} completionHandler:nil];
      return YES;
    }
  }

  NSString *currentDomain = currentURL.host;
  NSString *targetDomain = targetURL.host;

  if (!currentDomain || !targetDomain) {
    return NO;
  }

  // Check if the navigationType is a link with an href attribute or
  // if the target of the navigation is a new window.
  if ((navigationAction.navigationType == WKNavigationTypeLinkActivated
      || !navigationAction.targetFrame)
      // If the current domain does not equal the target domain,
      // the assumption is the user is navigating away from the site.
      && ![currentDomain isEqualToString: targetDomain]) {
     // 4. Open the URL in a SFSafariViewController.
    SFSafariViewController *safariViewController =
        [[SFSafariViewController alloc] initWithURL:targetURL];
    [self presentViewController:safariViewController animated:YES
        completion:nil];
    return YES;
  }

  return NO;
}

Kiểm tra thành phần điều hướng trang

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

https://google.github.io/webview-ads/test/#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 này 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 kiểm thử không đặt lại về 0 để xác thực trạng thái trang đã được giữ nguyên.