Если в вашем приложении для показа веб-контента используется WKWebView, рекомендуем оптимизировать обработку кликов по следующим причинам:
-
WKWebViewне поддерживает просмотр страниц на вкладках. По умолчанию клики по объявлениям, которые должны открывать новую вкладку, не приводят ни к каким действиям.
При клике по объявлению, которое открывается в той же вкладке, страница перезагружается. Вы можете настроить принудительное открытие кликов по объявлениям за пределами
WKWebView, например если вы размещаете игры HTML5 и хотите сохранять состояние каждой игры.Автозаполнение не поддерживает данные кредитных карт в
WKWebView. Это может привести к снижению количества конверсий в электронной торговле для рекламодателей, что негативно скажется на монетизации веб-контента.
- Вход с аккаунтом Google не поддерживается в
WKWebView.
В этом руководстве приведены рекомендации по оптимизации поведения при клике в мобильных веб-представлениях с сохранением контента.
Требования
- Выполните инструкции из руководства Настройка веб-просмотра.
Реализация
Для атрибута target href в ссылках объявлений можно задать одно из следующих значений: _blank, _top, _self или _parent.
Ссылки в объявлениях также могут содержать функции JavaScript, например window.open(url, "_blank").
В таблице ниже описано, как каждая из этих ссылок работает в представлении WebView.
href целевой атрибут |
Поведение по умолчанию при нажатии на WKWebView |
|---|---|
target="_blank" |
Ссылка не обрабатывается веб-просмотром. |
target="_top" |
Перезагрузить ссылку в существующем веб-просмотре. |
target="_self" |
Перезагрузить ссылку в существующем веб-просмотре. |
target="_parent" |
Перезагрузить ссылку в существующем веб-просмотре. |
| Функция JavaScript | Поведение по умолчанию при нажатии на WKWebView |
window.open(url, "_blank") |
Ссылка не обрабатывается веб-просмотром. |
Чтобы оптимизировать поведение кликов в экземпляре WKWebView, выполните следующие действия:
Задайте
WKUIDelegateв экземпляреWKWebView.- Реализуйте
webView(_:createWebViewWith:for:windowFeatures:).
- Реализуйте
Задайте
WKNavigationDelegateв экземпляреWKWebView.- Реализуйте
webView(_:decidePolicyFor:decisionHandler:).
- Реализуйте
Решите, нужно ли оптимизировать поведение URL клика.
Проверьте, является ли свойство
navigationTypeобъектаWKNavigationActionтипом клика, который вы хотите оптимизировать. В примере кода проверяется наличие.linkActivated, что относится только к кликам по ссылкам с атрибутомhref.Проверьте свойство
targetFrameобъектаWKNavigationAction. Если возвращается значениеnil, это означает, что целевой объект навигации – новое окно. ПосколькуWKWebViewне может обработать этот клик, его нужно обработать вручную.
Решите, где открывать URL: во внешнем браузере (
SFSafariViewController) или в существующем веб-просмотре. В этом фрагменте кода показано, как открывать URL, ведущие за пределы сайта, с помощьюSFSafariViewController.
Пример кода
В приведенном ниже фрагменте кода показано, как оптимизировать поведение кликов в WebView. Например, он проверяет, отличается ли текущий домен от целевого. Это лишь один из возможных подходов. Вы можете использовать другие критерии.
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.
- При возвращении в приложение счетчик на тестовой странице не сбрасывается до нуля, чтобы подтвердить, что состояние страницы было сохранено.