Optimiser le comportement en termes de clics sur WKWebView

Si votre iOS application utiliseWKWebView pour afficher du contenu Web, vous pouvez envisager d'optimiser le comportement des clics pour les raisons suivantes:

  • WKWebView n'est pas compatible avec la Par défaut, les clics sur des annonces qui tentent d'ouvrir un nouvel onglet n'ont aucun effet.

  • Les clics sur des annonces qui s'ouvrent dans le même onglet permettent d'actualiser la page. Vous pouvez forcer l'ouverture des clics sur des annonces en dehors de WKWebView, par exemple si vous hébergez des jeux H5 et que vous souhaitez maintenir l'état de chaque jeu.

  • La saisie automatique n'est pas compatible avec les informations de carte de crédit saisies dans le pays suivant : WKWebView. Cela peut réduire le nombre de conversions e-commerce pour les annonceurs, ce qui peut avoir un impact négatif sur la monétisation du contenu Web.

Ce guide présente les étapes recommandées pour optimiser le comportement des clics dans les vues Web mobile tout en conservant le contenu de la vue Web.

Prérequis

Implémentation

L'attribut cible href des liens d'annonces peut être défini sur _blank, _top, _self ou _parent. Avec Ad Manager, vous pouvez définir l'attribut cible sur _blank ou _top en définissant les annonces pour qu'elles s'ouvrent dans un nouvel onglet ou une nouvelle fenêtre. Les liens d'annonces peuvent également contenir des fonctions JavaScript telles que window.open(url, "_blank").

Le tableau suivant décrit le comportement de chacun de ces liens dans une vue Web.

href attribut cible Comportement par défaut des clics WKWebView
target="_blank" Lien non géré par la vue Web.
target="_top" Actualisez le lien dans la vue Web existante.
target="_self" Actualisez le lien dans la vue Web existante.
target="_parent" Actualisez le lien dans la vue Web existante.
Fonction JavaScript Comportement par défaut des clics WKWebView
window.open(url, "_blank") Lien non géré par la vue Web.

Procédez comme suit pour optimiser le comportement des clics dans votre instanceWKWebView :

  1. Définissez WKUIDelegate sur votre instance WKWebView.

  2. Définissez WKNavigationDelegate sur votre instance WKWebView.

  3. Déterminez si le comportement de l'URL de suivi des clics doit être optimisé.

    • Vérifiez si la propriété navigationType de l'objet WKNavigationAction correspond à un type de clic que vous souhaitez optimiser. L'extrait de code vérifie la présence de .linkActivated, qui ne s'applique qu'aux clics sur un lien comportant un attribut href.

    • Vérifiez la propriété targetFrame de l'objet WKNavigationAction. Si la valeur nil est renvoyée, cela signifie que la cible de la navigation est une nouvelle fenêtre. Étant donné que WKWebView ne peut pas gérer ce clic, ceux-ci doivent être gérés manuellement.

  4. Indiquez si vous souhaitez ouvrir l'URL dans un navigateur externe, SFSafariViewController ou dans la vue Web existante. L'extrait de code montre comment ouvrir des URL externes au site en présentant un SFSafariViewController.

Exemple de code

L'extrait de code suivant montre comment optimiser le comportement des clics vers la vue Web. Par exemple, elle vérifie si le domaine actuel est différent du domaine cible. Il ne s'agit que d'une approche parmi tant d'autres, car les critères utilisés peuvent varier.

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

Tester la navigation sur les pages

Pour tester les modifications apportées à la navigation sur les pages, chargez

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

dans la vue Web. Cliquez sur chacun des différents types de liens pour voir leur comportement dans votre application.

Voici quelques points à vérifier :

  • Chaque lien ouvre l'URL prévue.
  • Lors du retour à l'application, le compteur de la page de test n'est pas réinitialisé pour vérifier que l'état de la page a bien été conservé.