Otimizar o comportamento de clique do WKWebView

Se o app usar a WKWebView para mostrar conteúdo da Web, considere otimizar o comportamento de clique pelos seguintes motivos:

  • O WKWebView não oferece suporte à navegação com guias. Os cliques em anúncios que tentam abrir uma nova guia não fazem nada por padrão.

  • Os cliques no anúncio que abrem na mesma guia recarregam a página. Talvez você queira forçar os cliques de anúncios a abrir 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 apresenta etapas recomendadas para otimizar o comportamento de cliques em visualizações da Web em dispositivos móveis, preservando o conteúdo.

Pré-requisitos

Implementação

Os links de anúncios podem ter o atributo de destino href definido como _blank, _top, _self ou _parent. Com o Ad Manager, é possível controlar o atributo de segmentação para ser _blank ou _top configurando os anúncios para abrir em uma nova guia ou janela. 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 de WKWebView
target="_blank" O link não é processado pela visualização da Web.
target="_top" Atualize o link na visualização da Web atual.
target="_self" Atualize o link na visualização da Web atual.
target="_parent" Atualize o link na visualização da Web atual.
Função JavaScript Comportamento de clique padrão de WKWebView
window.open(url, "_blank") O 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 WKUIDelegate na sua instância WKWebView.

  2. Defina WKNavigationDelegate na sua instância 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, significa que o destino da navegação é uma nova janela. Como WKWebView não pode processar esse clique, ele precisa ser processado manualmente.

  4. Decida se o URL será aberto em um navegador externo, SFSafariViewController ou na visualização da Web atual. O snippet de código mostra como abrir URLs que saem do site apresentando 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. Como 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? {
    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;
}

Testar a navegação na página

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

https://webview-api-for-ads-test.glitch.me#click-behavior-tests

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

Veja alguns pontos a serem verificados:

  • Cada link abre o URL desejado.
  • 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.