Otimizar o comportamento de clique da WebView

Se o app usa WebView para mostrar conteúdo da Web, considere otimizar o comportamento de clique pelos seguintes motivos:

  • WebView não oferece suporte a esquemas de URL personalizados, que podem ser retornados em anúncios se o destino do clique for um app separado. Por exemplo, um URL de clique do Google Play pode usar market://.

Este guia apresenta etapas recomendadas para otimizar o comportamento de cliques em visualizações da Web em dispositivos móveis, preservando o conteúdo.

Pré-requisitos

Implementação

Siga estas etapas para otimizar o comportamento de clique na sua instância do WebView:

  1. Substitua shouldOverrideUrlLoading() no WebViewClient. Esse método é chamado quando um URL está prestes a ser carregado no WebView atual.

  2. Determine se o comportamento do URL de clique será substituído.

    O exemplo de código verifica se o domínio atual é diferente do domínio de destino. Essa é apenas uma abordagem, já que os critérios usados podem variar.

  3. Decida se você quer abrir o URL em um navegador externo, nas Guias personalizadas do Android ou na visualização da Web atual. Este guia mostra como abrir URLs que saem do site ao iniciar as guias personalizadas do Android.

Exemplo de código

Primeiro, adicione a dependência androidx.browser ao arquivo build.gradle do módulo, geralmente app/build.gradle. Isso é necessário para as Custom Tabs:

dependencies {
  implementation 'androidx.browser:browser:1.5.0'
}

O snippet de código abaixo mostra como 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
      }
    }
  }
}

Testar a navegação na página

Para testar as mudanças na navegação da página, carregue

https://webview-api-for-ads-test.glitch.me#click-behavior-tests

na visualização da Web. Clique em cada um dos tipos de link para conferir como eles se comportam no app.

Veja alguns pontos a serem verificados:

  • Cada link abre o URL desejado.
  • 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.