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