Otimizar o comportamento de clique da WebView

Caso seu Android app use WebView para mostrar conteúdo da Web, otimize o comportamento de cliques pelos seguintes motivos:

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

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

Implementação

Siga estas etapas para otimizar o comportamento de clique na instânciaWebView :

  1. Modifique 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 deve ser substituído.

    O snippet de código abaixo 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, em guias personalizadas do Android ou na visualização da Web já existente. Este guia mostra como abrir URLs navegando para fora do site iniciando guias personalizadas do Android.

Exemplo de código

Primeiro, adicione a dependência androidx.browser ao arquivo build.gradle do módulo, normalmente app/build.gradle. Isso é necessário para guias personalizadas:

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

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.