Si votre application utilise WKWebView
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 navigation par onglets. Par défaut, les clics sur les annonces qui tentent d'ouvrir un nouvel onglet ne produisent aucun effet.
Les clics sur les annonces qui s'ouvrent dans le même onglet rechargent la page. Vous pouvez forcer les clics sur les annonces à s'ouvrir en dehors de
WKWebView
, par exemple si vous hébergez des jeux H5 et que vous souhaitez conserver l'état de chaque jeu.La saisie automatique n'est pas compatible avec les informations de carte de crédit dans
WKWebView
. Cela pourrait entraîner moins de conversions d'e-commerce pour les annonceurs, ce qui aura un impact négatif sur la monétisation du contenu Web.
- Google Sign-In n'est pas compatible avec
WKWebView
.
Ce guide présente les étapes recommandées pour optimiser le comportement des clics dans les vues Web mobiles tout en préservant le contenu de la vue Web.
Prérequis
- Suivez le guide Configurer la vue Web.
Implémentation
L'attribut cible href
des liens vers les annonces peut être défini sur _blank
, _top
, _self
ou _parent
.
Les liens vers les 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.
Attribut cible href |
Comportement par défaut des clics sur 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 sur WKWebView |
window.open(url, "_blank") |
Lien non géré par la vue Web. |
Pour optimiser le comportement des clics dans votre instance WKWebView
:
Définissez
WKUIDelegate
sur votre instanceWKWebView
.- Implémentez
webView(_:createWebViewWith:for:windowFeatures:)
.
- Implémentez
Définissez
WKNavigationDelegate
sur votre instanceWKWebView
.- Implémentez
webView(_:decidePolicyFor:decisionHandler:)
.
- Implémentez
Déterminez si vous souhaitez optimiser le comportement de l'URL de clic.
Vérifiez si la propriété
navigationType
de l'objetWKNavigationAction
correspond à un type de clic que vous souhaitez optimiser. L'exemple de code vérifie.linkActivated
, qui ne s'applique qu'aux clics sur un lien avec un attributhref
.Vérifiez la propriété
targetFrame
sur l'objetWKNavigationAction
. Si elle renvoienil
, cela signifie que la cible de la navigation est une nouvelle fenêtre. Étant donné queWKWebView
ne peut pas gérer ce clic, ces clics doivent être gérés manuellement.
Déterminez si vous souhaitez ouvrir l'URL dans un navigateur externe,
SFSafariViewController
ou la vue Web existante. L'extrait de code montre comment ouvrir des URL qui quittent le site en présentant unSFSafariViewController
.
Exemple de code
L'extrait de code suivant montre comment optimiser le comportement de clic dans la vue Web. Par exemple, il vérifie si le domaine actuel est différent du domaine cible. Il ne s'agit là que d'une approche parmi d'autres, car les critères que vous utilisez 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 vos 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 votre vue Web. Cliquez sur chacun des différents types de liens pour voir comment ils se comportent dans votre application.
Voici quelques points à vérifier :
- Chaque lien ouvre l'URL souhaitée.
- Lorsque vous revenez à l'application, le compteur de la page de test n'est pas réinitialisé à zéro pour valider que l'état de la page a été préservé.