Optimiza el comportamiento de clics de WKWebView

Si tu iOS app usa WKWebView para mostrar contenido web, tal vez sea conveniente que optimices el comportamiento de los clics por los siguientes motivos:

  • WKWebView no admite la con la pestaña de navegación. Los clics en anuncios que intentan abrir una pestaña nueva no actúan en absoluto de forma predeterminada.

  • Los clics en el anuncio que se abren en la misma pestaña vuelven a cargar la página. Es posible que desees forzar la apertura de clics en los anuncios fuera de la WKWebView, por ejemplo, si alojas juegos H5 y deseas mantener el estado de cada juego.

  • La función Autocompletar no admite datos de tarjetas de crédito en WKWebView. Esto podría generar menos conversiones de comercio electrónico para los anunciantes, lo que afectará 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 en dispositivos móviles y, al mismo tiempo, preservar el contenido de las vistas web.

Requisitos previos

Implementación

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

href atributo de destino Comportamiento predeterminado de clics de WKWebView
target="_blank" Vínculo no administrado por 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") Vínculo no administrado por la vista web.

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

  1. Configura WKUIDelegate en tu instancia de WKWebView.

  2. Configura WKNavigationDelegate en tu instancia de WKWebView.

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

    • Verifica si la propiedad navigationType del objeto WKNavigationAction es un tipo de clic que deseas optimizar. El fragmento de código verifica .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 destino de la navegación es una ventana nueva. Dado que WKWebView no puede procesar ese clic, debes controlarlos 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 si sales del sitio mediante la presentación de un SFSafariViewController.

Ejemplo de código

En el siguiente fragmento de código, se muestra cómo optimizar el comportamiento de clics de las vistas web. A modo de ejemplo, verifica si el dominio actual es diferente del dominio de destino. Este es solo un enfoque, ya que los criterios que utilizas 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 la 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 regresas 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.