WebViews are great for seamlessly integrating your own web content into your app. When your first party content includes links to websites not owned by you, it can make sense to open these in a Custom Tab instead of the WebView. This has two benefits:
- The first party UX is clearly separated from the 3P web content UX.
- 3P web sites benefit from cookies being shared with the default browser.
To implement this, override shouldOverrideUrlLoading in your WebViewClient. WebView calls this method before it navigates to a link that the user taps. Return false to let the WebView load your own content, or open the link in a Custom Tab and return true to cancel the navigation in the WebView:
val webView = findViewById<WebView>(R.id.webview)
webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(
view: WebView,
request: WebResourceRequest
): Boolean {
val uri = request.url
if (uri.host == "www.my-own-domain.com") {
return false
}
CustomTabsIntent.Builder()
.build()
.launchUrl(view.context, uri)
return true
}
}