앱에서 WKWebView를 사용하여 웹 콘텐츠를 표시하는 경우 다음과 같은 이유로 클릭 동작을 최적화하는 것이 좋습니다.
- WKWebView는 탭 브라우징을 지원하지 않습니다. 새 탭을 열려고 시도하는 광고 클릭은 기본적으로 아무 작업도 하지 않습니다.
동일한 탭에서 열리는 광고 클릭은 페이지를 새로고침합니다. 예를 들어 H5 게임을 호스팅하고 각 게임의 상태를 유지하려는 경우 광고 클릭이
WKWebView
외부에서 열리도록 강제할 수 있습니다.자동 완성은
WKWebView
의 신용카드 정보를 지원하지 않습니다. 이로 인해 광고주의 전자상거래 전환이 줄어들어 웹 콘텐츠의 수익 창출에 부정적인 영향을 미칠 수 있습니다.
- Google 로그인은
WKWebView
에서 지원되지 않습니다.
이 가이드에서는 웹 뷰 콘텐츠를 유지하면서 모바일 웹 뷰의 클릭 동작을 최적화하기 위한 권장 단계를 제공합니다.
기본 요건
- 웹 뷰 설정 가이드를 완료합니다.
구현
광고 링크의 href
타겟 속성은 _blank
, _top
, _self
또는 _parent
으로 설정할 수 있습니다.
Ad Manager를 사용하면 새 탭이나 창에서 광고가 열리도록 설정하여 타겟 속성을 _blank
또는 _top
로 제어할 수 있습니다.
광고 링크에는 window.open(url, "_blank")
와 같은 JavaScript 함수도 포함될 수 있습니다.
다음 표에서는 웹 뷰에서 이러한 각 링크가 작동하는 방식을 설명합니다.
href 타겟 속성 |
기본 WKWebView 클릭 동작 |
---|---|
target="_blank" |
웹 뷰에서 링크를 처리하지 않음 |
target="_top" |
기존 웹 보기에서 링크를 새로고침합니다. |
target="_self" |
기존 웹 보기에서 링크를 새로고침합니다. |
target="_parent" |
기존 웹 보기에서 링크를 새로고침합니다. |
JavaScript 함수 | 기본 WKWebView 클릭 동작 |
window.open(url, "_blank") |
웹 뷰에서 링크를 처리하지 않음 |
다음 단계에 따라 WKWebView
인스턴스에서 클릭 동작을 최적화하세요.
WKWebView
인스턴스에서WKUIDelegate
을 설정합니다.WKWebView
인스턴스에서WKNavigationDelegate
을 설정합니다.클릭 URL의 동작을 최적화할지 여부를 결정합니다.
WKNavigationAction
객체의navigationType
속성이 최적화하려는 클릭 유형인지 확인합니다. 코드 예시에서는.linkActivated
를 확인합니다. 이는href
속성이 있는 링크 클릭에만 적용됩니다.WKNavigationAction
객체의targetFrame
속성을 확인합니다.nil
를 반환하면 탐색의 타겟이 새 창임을 의미합니다.WKWebView
는 해당 클릭을 처리할 수 없으므로 이러한 클릭은 수동으로 처리해야 합니다.
외부 브라우저(
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? {
// 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;
}
페이지 탐색 테스트
페이지 탐색 변경사항을 테스트하려면
https://google.github.io/webview-ads/test/#click-behavior-tests
웹 뷰에 삽입합니다. 다양한 링크 유형을 각각 클릭하여 앱에서 어떻게 작동하는지 확인합니다.
다음과 같은 사항을 확인해 보시기 바랍니다.
- 각 링크는 의도한 URL을 엽니다.
- 앱으로 돌아가면 페이지 상태가 유지되었는지 확인하기 위해 테스트 페이지의 카운터가 0으로 재설정되지 않습니다.