앱에서 WKWebView를 사용하여 웹 콘텐츠를 표시하는 경우 다음과 같은 이유로 클릭 동작을 최적화하는 것이 좋습니다.
- WKWebView는 탭 브라우징을 지원하지 않습니다. 새 탭을 열려고 하는 광고 클릭은 기본적으로 아무 작업도 수행하지 않습니다.
같은 탭에서 열리는 광고 클릭은 페이지를 새로고침합니다. 예를 들어 H5 게임을 호스팅하고 각 게임의 상태를 유지하려는 경우 광고 클릭이
WKWebView외부에서 열리도록 강제할 수 있습니다.WKWebView에서는 자동 완성에서 신용카드 정보를 지원하지 않습니다. 이로 인해 광고주의 전자상거래 전환이 줄어들어 웹 콘텐츠의 수익 창출에 부정적인 영향을 미칠 수 있습니다.
- Google 로그인은
WKWebView에서 지원되지 않습니다.
이 가이드에서는 웹뷰 콘텐츠를 보존하면서 모바일 웹뷰의 클릭 동작을 최적화하는 데 권장되는 단계를 제공합니다.
기본 요건
- 웹 뷰 설정 가이드를 완료합니다.
구현
광고 링크에는 _blank, _top, _self 또는 _parent로 설정된 href 타겟 속성이 있을 수 있습니다.
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속성이 최적화하려는 클릭 유형인지 확인합니다. 코드 예는href속성이 있는 링크 클릭에만 적용되는.linkActivated를 확인합니다.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으로 재설정되지 않아 페이지 상태가 유지되었는지 확인합니다.