WebView 클릭 동작 최적화

Android 앱에서WebView 를 사용하여 웹 콘텐츠를 표시한다면 다음과 같은 이유로 클릭 동작을 최적화하는 것이 좋습니다.

  • WebView탭 탐색을 지원하지 않습니다. 링크를 클릭하면 기본 웹브라우저에서 콘텐츠가 열립니다.
  • WebView는 클릭 도착 페이지가 별도의 앱으로 연결되는 경우 광고에 반환될 수 있는 맞춤 URL 스키마를 지원하지 않습니다. 예를 들어 Google Play 클릭연결 URL에는 market://를 사용할 수 있습니다.

이 가이드에서는 웹 보기 콘텐츠를 유지하면서 모바일 웹 보기에서 클릭 동작을 최적화하기 위한 권장 단계를 제공합니다.

기본 요건

구현

WebView 인스턴스에서 클릭 동작을 최적화하려면 다음 단계를 따르세요.

  1. WebViewClient에서 shouldOverrideUrlLoading()를 재정의합니다. 이 메서드는 URL이 현재 WebView에 로드되려고 할 때 호출됩니다.

  2. 클릭 URL의 동작을 재정의할지 여부를 결정합니다.

    아래 코드 스니펫은 현재 도메인이 대상 도메인과 다른지 확인합니다. 이는 사용하는 기준이 다를 수 있으므로 이는 하나의 방법일 뿐입니다.

  3. 외부 브라우저, Android 맞춤 탭 또는 기존 웹 뷰 내에서 URL을 열지 결정합니다. 이 가이드에서는 Android 맞춤 탭을 실행하여 사이트에서 벗어나는 URL을 여는 방법을 설명합니다.

코드 예시

먼저 androidx.browser 종속 항목을 모듈 수준 build.gradle 파일(일반적으로 app/build.gradle)에 추가합니다. 맞춤 탭의 필수 속성입니다.

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

다음 코드 스니펫은 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
      }
    }
  }
}

페이지 탐색 테스트

페이지 탐색 변경사항을 테스트하려면

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

웹 뷰로 가져올 수 있습니다 각 링크 유형을 클릭하여 앱에서 어떻게 작동하는지 확인합니다.

다음과 같은 사항을 확인해 보시기 바랍니다.

  • 각 링크를 통해 의도한 URL이 열립니다.
  • 앱으로 돌아가면 페이지 상태가 유지되었는지 확인하기 위해 테스트 페이지의 카운터가 0으로 재설정되지 않습니다.