Optimiza el comportamiento de clics de WKWebView

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 que los clics en el anuncio 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.

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

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:

  1. Configura WKUIDelegate en tu instancia de WKWebView.

  2. Configura WKNavigationDelegate en tu instancia de WKWebView.

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

    • Comprueba si la propiedad navigationType en el objeto WKNavigationAction 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 atributo href.

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

  4. 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 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. 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? {
    // 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 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.