Se o app usa
WKWebView para mostrar conteúdo da Web, talvez seja interessante
otimizar o comportamento de clique pelos seguintes motivos:
-
WKWebViewnão aceita navegação com guias. Os cliques no anúncio que tentam abrir uma nova guia não fazem nada por padrão.
Os cliques no anúncio que são abertos na mesma guia recarregam a página. Talvez você queira forçar os cliques no anúncio a serem abertos fora da
WKWebView, por exemplo, se você hospedar jogos em H5 e quiser manter o estado de cada jogo.O preenchimento automático não aceita informações de cartão de crédito em
WKWebView. Isso pode levar a menos conversões de comércio eletrônico para os anunciantes, afetando negativamente a monetização do conteúdo da Web.
- O login do Google
não é
aceito em
WKWebView.
Este guia fornece etapas recomendadas para otimizar o comportamento de clique em visualizações da Web para dispositivos móveis, preservando o conteúdo da visualização da Web.
Pré-requisitos
- Leia o 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 da WKWebView |
|---|---|
target="_blank" |
Link não processado pela visualização da Web. |
target="_top" |
Recarregar o link na visualização da Web atual. |
target="_self" |
Recarregar o link na visualização da Web atual. |
target="_parent" |
Recarregar o link na visualização da Web atual. |
| Função JavaScript | Comportamento de clique padrão da WKWebView |
window.open(url, "_blank") |
Link não processado pela visualização da Web. |
Siga estas etapas para otimizar o comportamento de clique na instância WKWebView:
Defina o
WKUIDelegatena instânciaWKWebView.Defina o
WKNavigationDelegatena instânciaWKWebView.- Implement
webView(_:decidePolicyFor:decisionHandler:).
- Implement
Determine se você quer otimizar o comportamento do URL de clique.
Verifique se a propriedade
navigationTypeno objetoWKNavigationActioné um tipo de clique que você quer otimizar. O exemplo de código verifica.linkActivatedque só se aplica a cliques em um link com um atributohref.Verifique a
targetFramepropriedade no objetoWKNavigationAction. Se ela retornarnil, significa que o destino da navegação é uma nova janela. ComoWKWebViewnão pode processar esse clique, eles precisam ser processados manualmente.
Decida se você quer abrir o URL em um navegador externo,
SFSafariViewController, ou na visualização da Web atual. O snippet de código mostra como abrir URLs que navegam para fora 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? {
// 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;
}
Testar a navegação nas páginas
Para testar as mudanças de navegação nas páginas, carregue
https://google.github.io/webview-ads/test/#click-behavior-tests
na visualização da Web. Clique em cada um dos diferentes tipos de link para ver como eles se comportam no seu app.
Veja alguns pontos a serem verificados:
- Cada link abre o URL pretendido.
- 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.