Se la tua app utilizza WKWebView per visualizzare i contenuti web, potresti voler ottimizzare il comportamento dei clic per i seguenti motivi:
- WKWebView non supporta la navigazione a 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 i clic sugli annunci ad aprirsi al di fuori di
WKWebView, ad esempio se ospiti giochi H5 e vuoi mantenere lo stato di ogni gioco.Il riempimento automatico non supporta i dati della carta di credito in
WKWebView. Ciò potrebbe comportare un minor numero di conversioni e-commerce per gli inserzionisti, influendo negativamente sulla monetizzazione dei contenuti web.
- Accedi con Google
non è
supportato in
WKWebView.
Questa guida fornisce i passaggi consigliati per ottimizzare il comportamento dei clic nelle visualizzazioni web mobile preservando i contenuti della visualizzazione web.
Prerequisiti
- Completa la guida Configurare la visualizzazione web.
Implementazione
I link degli annunci possono avere l'attributo target href impostato su _blank, _top,
_self o _parent.
Con Ad Manager puoi controllare l'attributo target da impostare su _blank o _top
impostando l'apertura degli annunci in una nuova scheda o
finestra.
I link degli annunci possono contenere anche funzioni JavaScript come
window.open(url, "_blank").
La seguente tabella descrive il comportamento di ciascuno di questi link in una visualizzazione web.
href attributo target |
Comportamento predefinito del 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 del clic WKWebView |
window.open(url, "_blank") |
Link non gestito dalla visualizzazione web. |
Per ottimizzare il comportamento dei clic nella tua istanza di WKWebView:
Imposta
WKUIDelegatesull'istanzaWKWebView.- Implementa
webView(_:createWebViewWith:for:windowFeatures:).
- Implementa
Imposta
WKNavigationDelegatesulla tua istanzaWKWebView.- Implementa
webView(_:decidePolicyFor:decisionHandler:).
- Implementa
Determina se ottimizzare il comportamento dell'URL di clic.
Verifica se la proprietà
navigationTypedell'oggettoWKNavigationActionè un tipo di clic che vuoi ottimizzare. L'esempio di codice verifica la presenza di.linkActivated, che si applica solo ai clic su un link con un attributohref.Controlla la proprietà
targetFramenell'oggettoWKNavigationAction. Se restituiscenil, significa che la destinazione della navigazione è una nuova finestra. PoichéWKWebViewnon può gestire questo clic, questi clic devono essere gestiti manualmente.
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 escono dal sito presentando unSFSafariViewController.
Codice di esempio
Il seguente snippet di codice mostra come ottimizzare il comportamento di clic della visualizzazione web. Ad esempio, controlla se il dominio attuale è diverso dal dominio di destinazione. Questo è solo un approccio, 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? {
// 3. Determine whether to optimize the behavior of the click URL.
if didHandleClickBehavior(
currentURL: webView.url,
navigationAction: navigationAction) {
print("URL opened in SFSafariViewController.")
}
return nil
}
// Implement the WKNavigationDelegate method.
func webView(
_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
{
// 3. Determine whether to optimize the behavior of the click URL.
if didHandleClickBehavior(
currentURL: webView.url,
navigationAction: navigationAction) {
return decisionHandler(.cancel)
}
decisionHandler(.allow)
}
// Implement a helper method to handle click behavior.
func didHandleClickBehavior(
currentURL: URL,
navigationAction: WKNavigationAction) -> Bool {
guard let targetURL = navigationAction.request.url else {
return false
}
// Handle custom URL schemes such as itms-apps:// by attempting to
// launch the corresponding application.
if navigationAction.navigationType == .linkActivated {
if let scheme = targetURL.scheme, !["http", "https"].contains(scheme) {
UIApplication.shared.open(targetURL, options: [:], completionHandler: nil)
return true
}
}
guard let currentDomain = currentURL.host,
let targetDomain = targetURL.host else {
return false
}
// 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 == .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 {
// 4. Open the URL in a SFSafariViewController.
let safariViewController = SFSafariViewController(url: targetURL)
present(safariViewController, animated: true)
return true
}
return false
}
}
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 {
// 3. Determine whether to optimize the behavior of the click URL.
if ([self didHandleClickBehaviorForCurrentURL: webView.URL
navigationAction: navigationAction]) {
NSLog(@"URL opened in SFSafariViewController.");
}
return nil;
}
// Implement the WKNavigationDelegate method.
- (void)webView:(WKWebView *)webView
decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
decisionHandler:
(void (^)(WKNavigationActionPolicy))decisionHandler {
// 3. Determine whether to optimize the behavior of the click URL.
if ([self didHandleClickBehaviorForCurrentURL: webView.URL
navigationAction: navigationAction]) {
decisionHandler(WKNavigationActionPolicyCancel);
return;
}
decisionHandler(WKNavigationActionPolicyAllow);
}
// Implement a helper method to handle click behavior.
- (BOOL)didHandleClickBehaviorForCurrentURL:(NSURL *)currentURL
navigationAction:(WKNavigationAction *)navigationAction {
NSURL *targetURL = navigationAction.request.URL;
// Handle custom URL schemes such as itms-apps:// by attempting to
// launch the corresponding application.
if (navigationAction.navigationType == WKNavigationTypeLinkActivated) {
NSString *scheme = targetURL.scheme;
if (![scheme isEqualToString:@"http"] && ![scheme isEqualToString:@"https"]) {
[UIApplication.sharedApplication openURL:targetURL options:@{} completionHandler:nil];
return YES;
}
}
NSString *currentDomain = currentURL.host;
NSString *targetDomain = targetURL.host;
if (!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:targetURL];
[self presentViewController:safariViewController animated:YES
completion:nil];
return YES;
}
return NO;
}
Testare la navigazione nelle pagine
Per testare le modifiche alla navigazione della pagina, carica
https://google.github.io/webview-ads/test/#click-behavior-tests
nella visualizzazione web. Fai clic su ciascun tipo 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.