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 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:

  • 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ể buộc các lượt nhấp vào quảng cáo mở ra 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 nhận được ít lượt chuyển đổi thương mại điện tử hơn, ảnh hưởng tiêu cực đến việc kiếm tiền từ nội dung trên web.

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

Đường liên kết quảng cáo có thể đặt thuộc tính mục tiêu 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 như window.open(url, "_blank").

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

Thuộc tính mục tiêu href Hành vi nhấp WKWebView mặc định
target="_blank" Đường liên kết không được xử lý bởi thành phần hiển thị 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 WKWebView mặc định
window.open(url, "_blank") Đường liên kết không được xử lý bởi thành phần hiển thị web.

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

  1. Đặt WKUIDelegate trên thực thể WKWebView.

  2. Đặt WKNavigationDelegate trên thực thể WKWebView.

  3. Xác định xem có nên tối ưu hoá hành vi của URL của lượt nhấp 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 các lượt nhấp vào đườ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, thì điều đó có nghĩa là mục tiêu 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 mở URL trong trình duyệt bên ngoài, SFSafariViewController hoặc chế độ xem web hiện có. Đoạn mã này cho biết cách mở các URL rời khỏi trang web bằng cách hiển thị 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 thành phần 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 phương pháp vì tiêu chí bạn sử dụng có thể khác nhau.

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? {
    guard let url = navigationAction.request.url,
        let currentDomain = webView.url?.host,
        let targetDomain = url.host else { return nil }

    // 3. Determine whether to optimize the behavior of the click URL.
    if didHandleClickBehavior(
        url: url,
        currentDomain: currentDomain,
        targetDomain: targetDomain,
        navigationAction: navigationAction) {
      print("URL opened in SFSafariViewController.")
    }

    return nil
  }

  // Implement the WKNavigationDelegate method.
  func webView(
      _ webView: WKWebView,
      decidePolicyFor navigationAction: WKNavigationAction,
      decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
  {
    guard let url = navigationAction.request.url,
        let currentDomain = webView.url?.host,
        let targetDomain = url.host else { return decisionHandler(.cancel) }

    // 3. Determine whether to optimize the behavior of the click URL.
    if didHandleClickBehavior(
        url: url,
        currentDomain: currentDomain,
        targetDomain: targetDomain,
        navigationAction: navigationAction) {
      return decisionHandler(.cancel)
    }

    decisionHandler(.allow)
  }

  // Implement a helper method to handle click behavior.
  func didHandleClickBehavior(
      url: URL,
      currentDomain: String,
      targetDomain: String,
      navigationAction: WKNavigationAction) -> Bool {
    // Check if the navigationType is a link with an href attribute or
    // if the target of the navigation is a new window.
    guard 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 else { return false }

    // 4.  Open the URL in a SFSafariViewController.
    let safariViewController = SFSafariViewController(url: url)
    present(safariViewController, animated: true)
    return true
  }
}

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 {
  NSURL *url = navigationAction.request.URL;
  NSString *currentDomain = webView.URL.host;
  NSString *targetDomain = navigationAction.request.URL.host;

  // 3. Determine whether to optimize the behavior of the click URL.
  if ([self didHandleClickBehaviorForURL: url
      currentDomain: currentDomain
      targetDomain: targetDomain
      navigationAction: navigationAction]) {
    NSLog(@"URL opened in SFSafariViewController.");
  }

  return nil;
}

// Implement the WKNavigationDelegate method.
- (void)webView:(WKWebView *)webView
    decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
                    decisionHandler:
                        (void (^)(WKNavigationActionPolicy))decisionHandler {
  NSURL *url = navigationAction.request.URL;
  NSString *currentDomain = webView.URL.host;
  NSString *targetDomain = navigationAction.request.URL.host;

  // 3. Determine whether to optimize the behavior of the click URL.
  if ([self didHandleClickBehaviorForURL: url
      currentDomain: currentDomain
      targetDomain: targetDomain
      navigationAction: navigationAction]) {

    decisionHandler(WKNavigationActionPolicyCancel);
    return;
  }

  decisionHandler(WKNavigationActionPolicyAllow);
}

// Implement a helper method to handle click behavior.
- (BOOL)didHandleClickBehaviorForURL:(NSURL *)url
                       currentDomain:(NSString *)currentDomain
                        targetDomain:(NSString *)targetDomain
                    navigationAction:(WKNavigationAction *)navigationAction {
  if (!url || !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:url];
    [self presentViewController:safariViewController animated:YES
        completion:nil];
    return YES;
  }

  return NO;
}

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.

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.