Si tu app usa WKWebView
para mostrar contenido web, te recomendamos que optimices el comportamiento de los clics por los siguientes motivos:
-
WKWebView
no admite la navegación con pestañas. Los clics en anuncios que intentan abrir una pestaña nueva no hacen nada de forma predeterminada.
Los clics en anuncios que se abren en la misma pestaña vuelven a cargar la página. Es posible que desees forzar los clics en el anuncio para que se abran fuera de
WKWebView
, por ejemplo, si alojas juegos H5 y deseas mantener el estado de cada juego.Autocompletar no admite información de tarjetas de crédito en
WKWebView
. Esto podría generar menos conversiones de comercio electrónico para los anunciantes, lo que afectaría negativamente la monetización del contenido web.
- El Acceso con Google no es compatible con
WKWebView
.
En esta guía, se proporcionan los pasos recomendados para optimizar el comportamiento de los clics en las vistas web para dispositivos móviles y, al mismo tiempo, preservar el contenido de la vista web.
Requisitos previos
- Completa la guía Configura la vista web.
Implementación
Los vínculos de anuncios pueden tener el atributo de segmentación href
configurado en _blank
, _top
, _self
o _parent
.
Los vínculos de anuncios también pueden contener funciones de JavaScript, como window.open(url, "_blank")
.
En la siguiente tabla, se describe cómo se comporta cada uno de estos vínculos en una vista web.
Atributo de destino href |
Comportamiento predeterminado de clics de WKWebView |
---|---|
target="_blank" |
La vista web no controla el vínculo. |
target="_top" |
Vuelve a cargar el vínculo en la vista web existente. |
target="_self" |
Vuelve a cargar el vínculo en la vista web existente. |
target="_parent" |
Vuelve a cargar el vínculo en la vista web existente. |
Función de JavaScript | Comportamiento predeterminado de clics de WKWebView |
window.open(url, "_blank") |
La vista web no controla el vínculo. |
Sigue estos pasos para optimizar el comportamiento de clics en tu instancia de WKWebView
:
Configura
WKUIDelegate
en tu instancia deWKWebView
.- Implementa
webView(_:createWebViewWith:for:windowFeatures:)
.
- Implementa
Configura
WKNavigationDelegate
en tu instancia deWKWebView
.- Implementa
webView(_:decidePolicyFor:decisionHandler:)
.
- Implementa
Determina si debes optimizar el comportamiento de la URL de clic.
Comprueba si la propiedad
navigationType
en el objetoWKNavigationAction
es un tipo de clic que deseas optimizar. El ejemplo de código busca.linkActivated
, que solo se aplica a los clics en un vínculo con un atributohref
.Verifica la propiedad
targetFrame
en el objetoWKNavigationAction
. Si muestranil
, significa que el destino de la navegación es una ventana nueva. Dado queWKWebView
no puede controlar ese clic, estos clics se deben controlar de forma manual.
Decide si quieres abrir la URL en un navegador externo,
SFSafariViewController
o en la vista web existente. En el fragmento de código, se muestra cómo abrir URLs que se alejan del sitio presentando unSFSafariViewController
.
Ejemplo de código
En el siguiente fragmento de código, se muestra cómo optimizar el comportamiento de clics de la vista web. Por ejemplo, verifica si el dominio actual es diferente del dominio de destino. Este es solo un enfoque, ya que los criterios que uses pueden variar.
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;
}
Cómo probar la navegación de tu página
Para probar los cambios en la navegación de la página, carga
https://webview-api-for-ads-test.glitch.me#click-behavior-tests
en tu vista web. Haz clic en cada uno de los diferentes tipos de vínculos para ver cómo se comportan en tu app.
A continuación, se indican algunos aspectos que puede verificar:
- Cada vínculo abre la URL deseada.
- Cuando vuelves a la app, el contador de la página de prueba no se restablece a cero para validar que se haya conservado el estado de la página.