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

Chọn nền tảng: Android iOS Android (Cũ)

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 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, 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 nên buộc lượt nhấp vào quảng cáo mở bên ngoài WKWebView, chẳng hạn như 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ể khiến nhà quảng cáo nhận được ít lượt chuyển đổi thương mại điện tử hơn, từ đó ảnh hưởng tiêu cực đến khả nă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 nên làm để tối ưu hoá hành vi nhấp trong chế độ xem web dành cho thiết bị di động, đồng thời 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 quảng cáo có thể có thuộc tính mục tiêu href được đặt thành _blank, _top, _self hoặc _parent. Với Ad Manager, bạn có thể kiểm soát thuộc tính mục tiêu thành _blank hoặc _top bằng cách đặt quảng cáo mở trong một thẻ hoặc cửa sổ mới. Đườ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 này trong một khung hiển thị web.

thuộc tính mục tiêu href Hành vi nhấp mặc định của WKWebView
target="_blank" Đường liên kết không được chế độ xem web xử lý.
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 mặc định của WKWebView
window.open(url, "_blank") Đường liên kết không được chế độ xem web xử lý.

Hãy làm theo các bước sau để tối ưu hoá hành vi nhấp chuột trong thực thể 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 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ì 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 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ở URL để chuyển hướng 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 chế độ xem web. Ví dụ: chính sách 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 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? {
    // 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 tính năng điều hướng trang

Để kiểm tra các thay đổi về cách đ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 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 đều 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.