Otimizar o comportamento de clique da WebView

Selecione a plataforma: Android (Beta) New-selected Android iOS

Se o app usa WebView para mostrar conteúdo da Web, talvez seja interessante otimizar o comportamento de cliques 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 oferece etapas recomendadas para otimizar o comportamento de cliques em visualizações da Web para dispositivos móveis , preservando o conteúdo da visualização da Web.

Pré-requisitos

Implementação

Siga estas etapas para otimizar o comportamento de cliques na WebView instância:

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

  2. Determine se você quer substituir o comportamento do URL de clique.

    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 navegando para fora de o site, iniciando as 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 as guias personalizadas:

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

O snippet de código a seguir 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 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
      }
    }
  }
}

Testar a navegação da página

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

https://google.github.io/webview-ads/test/#click-behavior-tests

na 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 é redefinido para zero para validar se o estado da página foi preservado.