Si tu app usa WebView
para mostrar contenido web, te recomendamos que optimices el comportamiento de los clics por los siguientes motivos:
-
WebView
no admite la navegación por pestañas. Si haces clic en un vínculo, se abrirá el contenido en el navegador web predeterminado.
WebView
no admite esquemas de URL personalizados, que podrían mostrarse en los anuncios si el destino del clic es una app diferente. Por ejemplo, una URL de clic de Google Play podría usarmarket://
.
- Acceso con Google y Acceder con Facebook no son compatibles con
WebView
.
En esta guía, se proporcionan los pasos recomendados para optimizar el comportamiento de los clics en las vistas web para dispositivos móviles y, al mismo tiempo, preservar el contenido de la vista web.
Requisitos previos
- Completa la guía Configura la vista web.
Implementación
Sigue estos pasos para optimizar el comportamiento de clics en tu instancia de WebView
:
Anula
shouldOverrideUrlLoading()
enWebViewClient
. Se llama a este método cuando se está a punto de cargar una URL en elWebView
actual.Determina si se debe anular el comportamiento de la URL de clic.
El ejemplo de código verifica si el dominio actual es diferente del dominio de destino. Este es solo un enfoque, ya que los criterios que uses podrían variar.
Decide si quieres abrir la URL en un navegador externo, en las pestañas personalizadas de Android o en la vista web existente. En esta guía, se muestra cómo abrir URLs que se alejan del sitio a través del lanzamiento de pestañas personalizadas de Android.
Ejemplo de código
Primero, agrega la dependencia de androidx.browser
al archivo build.gradle
a nivel del módulo, generalmente app/build.gradle
. Esto es obligatorio para las pestañas personalizadas:
dependencies {
implementation 'androidx.browser:browser:1.5.0'
}
En el siguiente fragmento de código, se muestra cómo implementar shouldOverrideUrlLoading()
:
Java
public class MainActivity extends AppCompatActivity {
private WebView webView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ... Register the WebView.
webView = new WebView(this);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(
new WebViewClient() {
// 1. Implement the web view click handler.
@Override
public boolean shouldOverrideUrlLoading(
WebView view,
WebResourceRequest request) {
// 2. Determine whether to override the behavior of the URL.
// If the target URL has no host, return early.
if (request.getUrl().getHost() == null) {
return false;
}
// Handle custom URL schemes such as market:// by attempting to
// launch the corresponding application in a new intent.
if (!request.getUrl().getScheme().equals("http")
&& !request.getUrl().getScheme().equals("https")) {
Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
// If the URL cannot be opened, return early.
try {
MainActivity.this.startActivity(intent);
} catch (ActivityNotFoundException exception) {
Log.d("TAG", "Failed to load URL with scheme:" + request.getUrl().getScheme());
}
return true;
}
String currentDomain;
// If the current URL's host cannot be found, return early.
try {
currentDomain = new URI(view.getUrl()).toURL().getHost();
} catch (URISyntaxException | MalformedURLException exception) {
// Malformed URL.
return false;
}
String targetDomain = request.getUrl().getHost();
// If the current domain equals the target domain, the
// assumption is the user is not navigating away from
// the site. Reload the URL within the existing web view.
if (currentDomain.equals(targetDomain)) {
return false;
}
// 3. User is navigating away from the site, open the URL in
// Custom Tabs to preserve the state of the web view.
CustomTabsIntent intent = new CustomTabsIntent.Builder().build();
intent.launchUrl(MainActivity.this, request.getUrl());
return true;
}
});
}
}
Kotlin
class MainActivity : AppCompatActivity() {
private lateinit var webView: WebView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ... Register the WebView.
webView.webViewClient = object : WebViewClient() {
// 1. Implement the web view click handler.
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
// 2. Determine whether to override the behavior of the URL.
// If the target URL has no host, return early.
request?.url?.host?.let { targetDomain ->
val currentDomain = URI(view?.url).toURL().host
// Handle custom URL schemes such as market:// by attempting to
// launch the corresponding application in a new intent.
if (!request.url.scheme.equals("http") &&
!request.url.scheme.equals("https")) {
val intent = Intent(Intent.ACTION_VIEW, request.url)
// If the URL cannot be opened, return early.
try {
this@MainActivity.startActivity(intent)
} catch (exception: ActivityNotFoundException) {
Log.d("TAG", "Failed to load URL with scheme: ${request.url.scheme}")
}
return true
}
// If the current domain equals the target domain, the
// assumption is the user is not navigating away from
// the site. Reload the URL within the existing web view.
if (currentDomain.equals(targetDomain)) {
return false
}
// 3. User is navigating away from the site, open the URL in
// Custom Tabs to preserve the state of the web view.
val customTabsIntent = CustomTabsIntent.Builder().build()
customTabsIntent.launchUrl(this@MainActivity, request.url)
return true
}
return false
}
}
}
}
Cómo probar la navegación de tu página
Para probar los cambios en la navegación de la página, carga
https://webview-api-for-ads-test.glitch.me#click-behavior-tests
en tu vista web. Haz clic en cada uno de los diferentes tipos de vínculos para ver cómo se comportan en tu app.
A continuación, se indican algunos aspectos que puede verificar:
- Cada vínculo abre la URL deseada.
- Cuando vuelves a la app, el contador de la página de prueba no se restablece a cero para validar que se haya conservado el estado de la página.