Ottimizzare il comportamento dei clic in WKWebView

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

  • WKWebView non supporta la navigazione a schede. I clic sull'annuncio che tentano di aprire una nuova scheda non hanno alcun effetto per impostazione predefinita.

  • I clic sull'annuncio che si aprono nella stessa scheda ricaricano la pagina. Potresti voler forzare l'apertura dei clic sugli 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 comportare un minor numero di conversioni e-commerce per gli inserzionisti, con ripercussioni negative sulla monetizzazione dei contenuti web.

Questa guida fornisce i passaggi consigliati per ottimizzare il comportamento dei clic nelle visualizzazioni del web mobile, preservando i contenuti della visualizzazione web.

Prerequisiti

Implementazione

I link degli annunci possono avere l'attributo target href impostato su _blank, _top, _self o _parent. I link degli annunci possono contenere anche funzioni JavaScript come window.open(url, "_blank").

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

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

Segui questi passaggi per ottimizzare il comportamento dei clic nella tuaWKWebView istanza:

  1. Imposta WKUIDelegate sulla tua istanza di WKWebView.

  2. Imposta WKNavigationDelegate sulla tua istanza WKWebView.

  3. Determinare se ottimizzare il comportamento dell'URL di clic.

    • Controlla se la proprietà navigationType nell'oggetto WKNavigationAction è un tipo di clic da ottimizzare. Lo snippet di codice controlla .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. WKWebView non può gestire questo clic, pertanto questi clic devono essere gestiti manualmente.

  4. Decidi se aprire l'URL in un browser esterno, SFSafariViewController, o nella vista web esistente. Lo snippet di codice mostra come aprire gli URL che escono dal sito presentando un SFSafariViewController.

Esempio di codice

Il seguente snippet di codice mostra come ottimizzare il comportamento dei clic nella visualizzazione web. Ad esempio, verifica se il dominio attuale è diverso da quello di destinazione. Questo è solo uno degli approcci, in quanto i criteri utilizzati possono 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 nelle pagine, carica

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

nella vista 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 confermare che lo stato della pagina è stato mantenuto.