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 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 portare a un calo delle conversioni di e-commerce per gli inserzionisti, con un impatto negativo 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 su dispositivi mobili, preservando al contempo i contenuti della visualizzazione web.
Prerequisiti
- Completa la guida Configurare la visualizzazione web.
Implementazione
L'attributo target href
dei link agli annunci può essere impostato su _blank
, _top
,
_self
o _parent
.
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:
Imposta
WKUIDelegate
sull'istanzaWKWebView
.- Implementa
webView(_:createWebViewWith:for:windowFeatures:)
.
- Implementa
Imposta
WKNavigationDelegate
sull'istanzaWKWebView
.- Implementa
webView(_:decidePolicyFor:decisionHandler:)
.
- Implementa
Determina se ottimizzare il comportamento dell'URL di clic.
Verifica se la proprietà
navigationType
nell'oggettoWKNavigationAction
è 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 attributohref
.Controlla la proprietà
targetFrame
nell'oggettoWKNavigationAction
. Se restituiscenil
, significa che la destinazione della navigazione è una nuova finestra. PoichéWKWebView
non 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 rimandano al di fuori del sito presentando unSFSafariViewController
.
Esempio di codice
Il seguente snippet di codice mostra come ottimizzare il comportamento dei clic nella visualizzazione web. Come 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? {
// 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;
}
Testa la navigazione nelle pagine
Per testare le modifiche alla navigazione nella pagina, carica
https://google.github.io/webview-ads/test/#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.