Optimiza el comportamiento de clics de WebView

Si tu Android app usa WebView para mostrar contenido web, tal vez sea conveniente que optimices el comportamiento de los clics por los siguientes motivos:

  • WebView no admite esquemas de URL personalizada que podrían mostrarse en los anuncios si el destino del clic es a 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 clics en las vistas web en dispositivos móviles y, al mismo tiempo, preservar el contenido de las vistas web.

Requisitos previos

Implementación

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

  1. Anula shouldOverrideUrlLoading() en el WebViewClient. Se llama a este método cuando una URL está a punto de cargarse en el WebView actual.

  2. Determina si se debe anular el comportamiento de la URL de clic.

    El siguiente fragmento de código verifica si el dominio actual es diferente del dominio de destino. Este es solo un enfoque, ya que los criterios que utilizas pueden variar.

  3. Decide si quieres abrir la URL en un navegador externo, en pestañas personalizadas de Android o dentro de la vista web existente. En esta guía, se muestra cómo abrir URLs si sales del sitio iniciando pestañas personalizadas de Android.

Ejemplo de código

Primero, agrega la dependencia androidx.browser al archivo build.gradle de nivel de módulo, que suele ser 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 URL(view.getUrl()).getHost();
            } catch (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 = URL(view?.url).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 la 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 regresas 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.