WKWebView 클릭 동작 최적화

iOS 앱에서WKWebView 를 사용하여 웹 콘텐츠를 표시한다면 다음과 같은 이유로 클릭 동작을 최적화하는 것이 좋습니다.

  • WKWebView 는 탭 탐색. 새 탭을 열려고 하는 광고 클릭은 기본적으로 아무 작업도 하지 않습니다.

  • 같은 탭에서 열리는 광고 클릭은 페이지를 새로고침합니다. 예를 들어 H5 게임을 호스팅하고 각 게임의 상태를 유지하려는 경우 WKWebView 외부에서 광고 클릭이 열리도록 할 수 있습니다.

  • WKWebView의 신용카드 정보는 자동 완성 기능이 지원되지 않습니다. 이로 인해 광고주의 전자상거래 전환이 줄어들어 웹 콘텐츠의 수익 창출에 부정적인 영향을 미칠 수 있습니다.

이 가이드에서는 웹 보기 콘텐츠를 유지하면서 모바일 웹 보기에서 클릭 동작을 최적화하기 위한 권장 단계를 제공합니다.

기본 요건

구현

광고 링크의 href 타겟 속성을 _blank, _top, _self 또는 _parent로 설정할 수 있습니다. 광고 링크에는 window.open(url, "_blank")와 같은 자바스크립트 함수도 포함될 수 있습니다.

다음 표는 각 링크가 웹 보기에서 어떻게 작동하는지 설명합니다.

대상 속성 href 기본 WKWebView 클릭 동작
target="_blank" 링크가 웹 보기에서 처리되지 않습니다.
target="_top" 기존 웹 보기에서 링크 새로고침
target="_self" 기존 웹 보기에서 링크 새로고침
target="_parent" 기존 웹 보기에서 링크 새로고침
자바스크립트 함수 기본 WKWebView 클릭 동작
window.open(url, "_blank") 링크가 웹 보기에서 처리되지 않습니다.

WKWebView 인스턴스에서 클릭 동작을 최적화하려면 다음 단계를 따르세요.

  1. WKWebView 인스턴스에서 WKUIDelegate를 설정합니다.

  2. WKWebView 인스턴스에서 WKNavigationDelegate를 설정합니다.

  3. 클릭 URL의 동작을 최적화할지 여부를 결정합니다.

    • WKNavigationAction 객체의 navigationType 속성이 최적화하려는 클릭 유형인지 확인합니다. 코드 스니펫href 속성이 있는 링크를 클릭하는 경우에만 적용되는 .linkActivated를 확인합니다.

    • WKNavigationAction 객체에서 targetFrame 속성을 확인합니다. nil를 반환하면 탐색 대상이 새 창이라는 의미입니다. WKWebView는 이러한 클릭을 처리할 수 없으므로 이러한 클릭은 수동으로 처리해야 합니다.

  4. 외부 브라우저, SFSafariViewController 또는 기존 웹 뷰에서 URL을 열지를 결정합니다. 이 코드 스니펫은 SFSafariViewController를 표시하여 사이트에서 벗어나는 URL을 여는 방법을 보여줍니다.

코드 예시

다음 코드 스니펫은 웹 보기 클릭 동작을 최적화하는 방법을 보여줍니다. 예를 들어 현재 도메인이 대상 도메인과 다른지 확인합니다. 이는 사용하는 기준이 다를 수 있으므로 이는 하나의 방법일 뿐입니다.

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이 열립니다.
  • 앱으로 돌아가면 페이지 상태가 유지되었는지 확인하기 위해 테스트 페이지의 카운터가 0으로 재설정되지 않습니다.