WKWebView のクリック動作を最適化する

iOS アプリでWKWebView を使用してウェブ コンテンツを表示する場合は、次の理由からクリック動作の最適化を検討することをおすすめします。

  • WKWebView タブ ブラウジングは タブ ブラウジング。広告をクリックして新しいタブを開こうとしたとき、デフォルトでは何も起こりません。

  • 同じタブで広告をクリックすると、ページが再読み込みされます。たとえば、H5 ゲームをホストしていて、各ゲームの状態を維持したい場合などは、広告クリックを WKWebView の外部で強制的に開くことができます。

  • 自動入力は WKWebView のクレジット カード情報に対応していません。これにより、広告主の e コマース コンバージョンが減少し、ウェブ コンテンツの収益化に悪影響が及ぶ可能性があります。

このガイドでは、ウェブビューのコンテンツを保持しながら、モバイルウェブビューのクリック動作を最適化するための推奨手順について説明します。

前提条件

実装

広告リンクでは、href ターゲット属性を _blank_top_self_parent のいずれかに設定できます。 広告リンクには、window.open(url, "_blank") などの JavaScript 関数を含めることもできます。

次の表に、ウェブビューでのこれらの各リンクの動作を示します。

href のターゲット属性 デフォルトの WKWebView クリック動作
target="_blank" リンクはウェブビューで処理されません
target="_top" 既存のウェブビューでリンクを再読み込みします。
target="_self" 既存のウェブビューでリンクを再読み込みします。
target="_parent" 既存のウェブビューでリンクを再読み込みします。
JavaScript 関数 デフォルトの WKWebView クリック動作
window.open(url, "_blank") リンクはウェブビューで処理されません

WKWebView インスタンスでクリック動作を最適化する手順は次のとおりです。

  1. WKWebView インスタンスで WKUIDelegate を設定します。

  2. WKWebView インスタンスで WKNavigationDelegate を設定します。

  3. クリック URL の動作を最適化するかどうかを決定します。

    • WKNavigationAction オブジェクトの navigationType プロパティが、最適化するクリックタイプかどうかを確認します。コード スニペットは、href 属性の付いたリンクのクリックにのみ適用される .linkActivated をチェックします。

    • WKNavigationAction オブジェクトの targetFrame プロパティを確認します。nil が返された場合は、ナビゲーションのターゲットが新しいウィンドウであることを意味します。このクリックは WKWebView では処理できないため、手動で処理する必要があります。

  4. URL を外部ブラウザ、SFSafariViewController、既存のウェブビューのどちらで開くかを決定します。このコード スニペットは、SFSafariViewController を提示して、サイトから移動する URL を開く方法を示しています。

サンプルコード

次のコード スニペットは、ウェブビューのクリック動作を最適化する方法を示しています。たとえば、現在のドメインが移行先ドメインと異なるかどうかを確認します。使用する基準は異なる場合があるため、これは 1 つのアプローチにすぎません。

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;
}

ページ ナビゲーションをテストする

ページ ナビゲーションの変更をテストするには、

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

ウェブビューに統合されます各リンクタイプをクリックして、アプリでの動作を確認します。

その際は、次の点をよくご確認ください。

  • 各リンクをクリックすると、目的の URL が開きます。
  • アプリに戻ったときに、ページの状態が保持されたことを確認するために、テストページのカウンタがゼロにリセットされることはありません。