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

Nếu iOS ứng dụng của bạn sử dụngWKWebView để 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:

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

  • Cá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 lượt nhấp vào quảng cáo mở ra 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ự động điền không hỗ trợ thông tin thẻ tín dụng trong WKWebView. Điều này có thể làm giảm số lượt chuyển đổi thương mại điện tử cho nhà quảng cáo, ảnh hưởng tiêu cực đến hoạt động kiếm tiền từ nội dung trên web.

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

Đườ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 đến 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 mỗi đường liên kết trong số này hoạt động trong chế độ xem web.

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

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

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

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

  3. Xác định xem có 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. Đoạn mã kiểm tra .linkActivated, mã này 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, tức là mục tiêu của quá trình đ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 hay chế độ xem web hiện có. Đoạn mã cho biết cách mở các URL rời khỏi trang web bằng cách thể hiện 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ụ: tính năng nà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.

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