Optimiza el comportamiento de clics de WebView

Si tu app utiliza WebView para mostrar contenido web, es posible que desees optimizar el comportamiento de los clics por los siguientes motivos:

  • WebView no admite esquemas de URL personalizados que podrían devolverse en los anuncios si el destino del clic es una app independiente. Por ejemplo, una URL de clic de Google Play podría usar market://.

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, conservar el contenido de la vista web.

Requisitos previos

Implementación

Sigue estos pasos para optimizar el comportamiento de los clics en tu instancia de WebView:

  1. Anula shouldOverrideUrlLoading() en WebViewClient. Se llama a este método cuando se está por cargar una URL en el WebView actual.

  2. Determina si se 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 pueden variar.

  3. Decide si abrir la URL en un navegador externo, en Android Custom Tabs o en la vista web existente. En esta guía, se muestra cómo abrir URLs que navegan fuera del sitio con el lanzamiento de pestañas personalizadas de Android.

Ejemplo de código

Primero, agrega la dependencia de androidx.browser a tu 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 and no scheme, return early.
            if (request.getUrl().getHost() == null && request.getUrl().getScheme() == 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 and no scheme, return early.
        if (request?.url?.host == null && request.url.scheme == null) {
          return false
        }
        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
        }

        val targetDomain = request.url.host

        // 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
      }
    }
  }
}

Prueba la navegación de tu página

Para probar los cambios en la navegación de la página, carga

https://google.github.io/webview-ads/test/#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 prevista.
  • Cuando vuelves a la app, el contador de la página de prueba no se restablece a cero para validar que se conservó el estado de la página.