Ottimizzare il comportamento dei clic in WKWebView

Se la tua app utilizza WKWebView per visualizzare contenuti web, ti consigliamo di ottimizzare il comportamento dei clic per i seguenti motivi:

  • WKWebView non supporta la navigazione con schede. Per impostazione predefinita, i clic sugli annunci che tentano di aprire una nuova scheda non fanno nulla.

  • I clic sugli annunci che si aprono nella stessa scheda ricaricano la pagina. Potresti voler forzare la chiusura degli annunci al di fuori di WKWebView, ad esempio se ospiti giochi H5 e vuoi mantenere lo stato di ogni gioco.

  • La compilazione automatica non supporta i dati della carta di credito in WKWebView. Ciò potrebbe portare a un calo delle conversioni di e-commerce per gli inserzionisti, con un impatto negativo sulla monetizzazione dei contenuti web.

Questa guida fornisce i passaggi consigliati per ottimizzare il comportamento dei clic nelle visualizzazioni web su dispositivi mobili, preservando al contempo i contenuti della visualizzazione web.

Prerequisiti

Implementazione

L'attributo target href dei link agli annunci può essere impostato su _blank, _top, _self o _parent. Con Ad Manager puoi impostare l'attributo target su _blank o _top impostando gli annunci in modo che si aprano in una nuova scheda o finestra. I link agli annunci possono contenere anche funzioni JavaScript come window.open(url, "_blank").

La tabella seguente descrive il comportamento di ciascuno di questi link in una visualizzazione web.

Attributo target href Comportamento predefinito dei clic WKWebView
target="_blank" Link non gestito dalla visualizzazione web.
target="_top" Ricarica il link nella visualizzazione web esistente.
target="_self" Ricarica il link nella visualizzazione web esistente.
target="_parent" Ricarica il link nella visualizzazione web esistente.
Funzione JavaScript Comportamento predefinito dei clic WKWebView
window.open(url, "_blank") Link non gestito dalla visualizzazione web.

Per ottimizzare il comportamento dei clic nella tua WKWebView istanza:

  1. Imposta WKUIDelegate sull'istanza WKWebView.

  2. Imposta WKNavigationDelegate sull'istanza WKWebView.

  3. Determina se ottimizzare il comportamento dell'URL dei clic.

    • Verifica se la proprietà navigationType nell'oggetto WKNavigationAction è un tipo di clic che vuoi ottimizzare. L'esempio di codice controlla la presenza di .linkActivated, che si applica solo ai clic su un link con un attributo href.

    • Controlla la proprietà targetFrame nell'oggetto WKNavigationAction. Se restituisce nil, significa che la destinazione della navigazione è una nuova finestra. Poiché WKWebView non può gestire questo clic, questi clic devono essere gestiti manualmente.

  4. Decidi se aprire l'URL in un browser esterno, SFSafariViewController, o nella visualizzazione web esistente. Lo snippet di codice mostra come aprire gli URL che rimandano al di fuori del sito presentando un SFSafariViewController.

Esempio di codice

Il seguente snippet di codice mostra come ottimizzare il comportamento dei clic nella visualizzazione web. Ad esempio, controlla se il dominio corrente è diverso dal dominio di destinazione. Questo è solo un approccio, in quanto i criteri che utilizzi potrebbero variare.

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;
}

Testare la navigazione nelle pagine

Per testare le modifiche alla navigazione nella pagina, carica

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

nella visualizzazione web. Fai clic su ciascuno dei diversi tipi di link per vedere come si comportano nella tua app.

Ecco alcuni aspetti da controllare:

  • Ogni link apre l'URL previsto.
  • Quando torni all'app, il contatore della pagina di test non viene reimpostato su zero per verificare che lo stato della pagina sia stato mantenuto.