Se o app usa
WKWebView
para mostrar conteúdo da Web, considere
otimizar o comportamento de clique pelos seguintes motivos:
-
O
WKWebView
não oferece suporte à navegação com guias. Os cliques em anúncios que tentam abrir uma nova guia não fazem nada por padrão.
Os cliques no anúncio que abrem na mesma guia recarregam a página. Talvez você queira forçar os cliques de anúncios a abrir fora do
WKWebView
, por exemplo, se você hospedar jogos H5 e quiser manter o estado de cada jogo.O preenchimento automático não é compatível com informações de cartão de crédito em
WKWebView
. Isso pode levar a menos conversões de e-commerce para os anunciantes, afetando negativamente a monetização do conteúdo da Web.
- O Login do Google
não é
compatível com
WKWebView
.
Este guia apresenta etapas recomendadas para otimizar o comportamento de cliques em visualizações da Web em dispositivos móveis, preservando o conteúdo.
Pré-requisitos
- Siga as instruções do guia Configurar a visualização da Web.
Implementação
Os links de anúncios podem ter o atributo de destino href
definido como _blank
, _top
,
_self
ou _parent
.
Os links de anúncios também podem conter funções JavaScript, como
window.open(url, "_blank")
.
A tabela a seguir descreve como cada um desses links se comporta em uma visualização da Web.
Atributo de destino href |
Comportamento de clique padrão de WKWebView |
---|---|
target="_blank" |
O link não é processado pela visualização da Web. |
target="_top" |
Atualize o link na visualização da Web. |
target="_self" |
Atualize o link na visualização da Web. |
target="_parent" |
Atualize o link na visualização da Web atual. |
Função JavaScript | Comportamento de clique padrão de WKWebView |
window.open(url, "_blank") |
O link não é processado pela visualização da Web. |
Siga estas etapas para otimizar o comportamento de clique na sua instância do WKWebView
:
Defina
WKUIDelegate
na sua instânciaWKWebView
.- Implemente
webView(_:createWebViewWith:for:windowFeatures:)
.
- Implemente
Defina
WKNavigationDelegate
na sua instânciaWKWebView
.- Implemente
webView(_:decidePolicyFor:decisionHandler:)
.
- Implemente
Determine se é necessário otimizar o comportamento do URL de clique.
Verifique se a propriedade
navigationType
no objetoWKNavigationAction
é um tipo de clique que você quer otimizar. O exemplo de código verifica.linkActivated
, que se aplica apenas a cliques em um link com um atributohref
.Verifique a propriedade
targetFrame
no objetoWKNavigationAction
. Se ele retornarnil
, significa que o destino da navegação é uma nova janela. ComoWKWebView
não pode processar esse clique, ele precisa ser processado manualmente.
Decida se o URL será aberto em um navegador externo,
SFSafariViewController
ou na visualização da Web atual. O snippet de código mostra como abrir URLs que saem do site apresentando umSFSafariViewController
.
Exemplo de código
O snippet de código a seguir mostra como otimizar o comportamento de clique da visualização da Web. Como exemplo, ele verifica se o domínio atual é diferente do domínio de destino. Essa é apenas uma abordagem, já que os critérios usados podem variar.
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;
}
Testar a navegação na página
Para testar as mudanças na navegação da página, carregue
https://webview-api-for-ads-test.glitch.me#click-behavior-tests
na visualização da Web. Clique em cada um dos tipos de link para conferir como eles se comportam no app.
Veja alguns pontos a serem verificados:
- Cada link abre o URL desejado.
- Ao retornar ao app, o contador da página de teste não é redefinido para zero para validar se o estado da página foi preservado.