Otimizar o comportamento de clique do WKWebView

Se o app usa WKWebView para mostrar conteúdo da Web, talvez seja interessante otimizar o comportamento de clique pelos seguintes motivos:

  • O WKWebView não é compatível com a navegação por guias. Por padrão, os cliques em anúncios que tentam abrir uma nova guia não fazem nada.

  • Os cliques em anúncios que abrem na mesma guia recarregam a página. Talvez você queira forçar os cliques de anúncios a serem abertos fora do WKWebView, por exemplo, se você hospedar jogos H5 e quiser manter o estado de cada jogo.

  • O preenchimento automático não é compatível com informações de cartão de crédito em WKWebView. Isso pode levar a menos conversões de e-commerce para os anunciantes, afetando negativamente a monetização do conteúdo da Web.

Este guia mostra as etapas recomendadas para otimizar o comportamento de clique em visualizações da Web para dispositivos móveis, preservando o conteúdo da visualização da Web.

Pré-requisitos

Implementação

Os links de anúncios podem ter o atributo de destino href definido como _blank, _top, _self ou _parent. Os links de anúncios também podem conter funções JavaScript, como window.open(url, "_blank").

A tabela a seguir descreve como cada um desses links se comporta em uma visualização da Web.

Atributo de destino href Comportamento de clique padrão do WKWebView
target="_blank" Link não processado pela visualização da Web.
target="_top" Recarregue o link na visualização da Web atual.
target="_self" Recarregue o link na visualização da Web atual.
target="_parent" Recarregue o link na visualização da Web atual.
Função JavaScript Comportamento de clique padrão do WKWebView
window.open(url, "_blank") Link não processado pela visualização da Web.

Siga estas etapas para otimizar o comportamento de clique na sua instância do WKWebView:

  1. Defina o WKUIDelegate na instância do WKWebView.

  2. Defina o WKNavigationDelegate na instância do WKWebView.

  3. Determine se é necessário otimizar o comportamento do URL de clique.

    • Verifique se a propriedade navigationType no objeto WKNavigationAction é um tipo de clique que você quer otimizar. O exemplo de código verifica .linkActivated que se aplica apenas a cliques em um link com um atributo href.

    • Verifique a propriedade targetFrame no objeto WKNavigationAction. Se ele retornar nil, isso significa que o destino da navegação é uma nova janela. Como o WKWebView não consegue processar esse clique, eles precisam ser processados manualmente.

  4. Decida se quer abrir o URL em um navegador externo, SFSafariViewController, ou na visualização da Web atual. O snippet de código mostra como abrir URLs navegando para fora do site ao apresentar um SFSafariViewController.

Exemplo de código

O snippet de código a seguir mostra como otimizar o comportamento de clique da visualização da Web. Por exemplo, ele verifica se o domínio atual é diferente do domínio de destino. Essa é apenas uma abordagem, já que os critérios usados podem 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;
}

Teste a navegação na página

Para testar as mudanças na navegação da página, carregue

https://google.github.io/webview-ads/test/#click-behavior-tests

na sua visualização da Web. Clique em cada um dos diferentes tipos de link para ver como eles se comportam no seu app.

Veja alguns pontos a serem verificados:

  • Cada link abre o URL pretendido.
  • Ao retornar ao app, o contador da página de teste não é redefinido para zero para validar se o estado da página foi preservado.