Caso seu iOS app use
WKWebView
para mostrar conteúdo da Web, otimize
o comportamento de cliques pelos seguintes motivos:
WKWebView
não oferece suporte à navegando com a guia. Os cliques no anúncio que tentam abrir uma nova guia não fazem nada por padrão.
Os cliques em anúncios que são abertos na mesma guia recarregam a página. Pode ser necessário forçar a abertura dos cliques no anúncio fora do
WKWebView
, por exemplo, se você hospeda jogos H5 e quer manter o estado de cada um deles.O preenchimento automático não oferece suporte a informações de cartão de crédito em
WKWebView
. Isso poderia 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 são
compatíveis com
WKWebView
.
Neste guia, apresentamos as etapas recomendadas para otimizar o comportamento de clique nas visualizações da Web para dispositivos móveis e preservar o conteúdo da visualização na Web.
Pré-requisitos
- Conclua 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 vista da Web.
href atributo de destino |
Comportamento de clique padrão de WKWebView |
---|---|
target="_blank" |
Link não processado pela vista da Web. |
target="_top" |
Atualize o link na visualização da Web existente. |
target="_self" |
Atualize o link na visualização da Web existente. |
target="_parent" |
Atualize o link na visualização da Web existente. |
Função JavaScript | Comportamento de clique padrão de WKWebView |
window.open(url, "_blank") |
Link não processado pela vista da Web. |
Siga estas etapas para otimizar o comportamento de clique na instânciaWKWebView
:
Defina o
WKUIDelegate
na instância doWKWebView
.- Implemente
webView(_:createWebViewWith:for:windowFeatures:)
.
- Implemente
Defina
WKNavigationDelegate
na instância doWKWebView
.- Implemente
webView(_:decidePolicyFor:decisionHandler:)
.
- Implemente
Determine se o comportamento do URL de clique deve ser otimizado.
Verifique se a propriedade
navigationType
no objetoWKNavigationAction
é um tipo de clique que você quer otimizar. O snippet de código verifica o.linkActivated
, que só se aplica a cliques em um link com um atributohref
.Verifique a propriedade
targetFrame
no objetoWKNavigationAction
. Se retornarnil
, o destino da navegação é uma nova janela. ComoWKWebView
não pode processar esse clique, ele precisa ser processado manualmente.
Decida se você quer abrir o URL em um navegador externo, o
SFSafariViewController
, ou na visualização da Web atual. O snippet de código mostra como abrir URLs navegando 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. Por exemplo, ela 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 nas páginas
Para testar as mudanças na navegação nas páginas, carregue
https://webview-api-for-ads-test.glitch.me#click-behavior-tests
à 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 será redefinido como zero para validar que o estado da página foi preservado.