Optimiza el comportamiento de clics

Selecciona la plataforma: Android (beta) Nuevo Android iOS

Si tu app utiliza WKWebView para mostrar contenido web, es posible que quieras considerar optimizar el comportamiento de 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 quieras forzar que los clics en anuncios se abran fuera de WKWebView, por ejemplo, si alojas juegos H5 y quieres mantener el estado de cada juego.

  • El autocompletado 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.

En esta guía, se proporcionan los pasos recomendados para optimizar el comportamiento de clics en las vistas web para dispositivos móviles y, al mismo tiempo, preservar el contenido de la vista web.

Requisitos previos

Implementación

Los vínculos de anuncios pueden tener el atributo de destino href configurado como _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 el comportamiento de cada uno de estos vínculos en una vista web.

Atributo de destino href Comportamiento predeterminado de clics de WKWebView
target="_blank" El vínculo no se controla en la vista web.
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") El vínculo no se controla en la vista web.

Sigue estos pasos para optimizar el comportamiento de clics en tu instancia de WKWebView:

  1. Configura WKUIDelegate en tu WKWebView instancia.

  2. Configura WKNavigationDelegate en tu WKWebView instancia.

  3. Determina si deseas optimizar el comportamiento de la URL de clics.

    • Verifica si la navigationType propiedad del objeto WKNavigationAction es un tipo de clic que deseas optimizar. En el ejemplo de código, se verifica para .linkActivated que solo se aplica a los clics en un vínculo con un atributo href.

    • Verifica la targetFrame propiedad del objeto WKNavigationAction. Si muestra nil, significa que el destino de la navegación es una ventana nueva. Como WKWebView no puede controlar ese clic, estos clics deben controlarse de forma manual.

  4. Decide si deseas abrir la URL en un navegador externo, SFSafariViewController, o la vista web existente. En el fragmento de código, se muestra cómo abrir URLs que navegan fuera del sitio presentando un SFSafariViewController.

Ejemplo de código

En el siguiente fragmento de código, se muestra cómo optimizar el comportamiento de clics de la vista web. Como ejemplo, se 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? {
    // 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;
}

Cómo probar la navegación de tu página

Para probar los cambios en la navegación de tu página, carga

https://google.github.io/webview-ads/test/#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 puedes 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 conservó el estado de la página.