Optimize WebView click behavior
Stay organized with collections
Save and categorize content based on your preferences.
AI-generated Key Takeaways
-
Android
WebView
has limitations with click behavior, like opening links in external browsers instead of within the app. -
This guide provides steps to optimize click behavior by overriding
shouldOverrideUrlLoading()
in yourWebViewClient
. -
You can customize link handling to open links in external browsers, Custom Tabs, or within the
WebView
itself based on criteria like the target domain. -
The guide includes code examples in Java and Kotlin to demonstrate how to implement this optimized click handling.
-
By implementing these steps, you improve user experience and maintain the state of your web view content.
If your app utilizes
WebView
to display web content, you might want
to consider optimizing click behavior for the following reasons:
-
WebView
doesn't support tabbed browsing. Clicking a link opens the content in the default web browser.
WebView
doesn't support custom URL schemes which could be returned in ads if the click destination is to a separate app. For example, a Google Play click-through URL might usemarket://
.
- Google Sign-in
and Facebook Sign-in
aren't
supported in
WebView
.
This guide provides recommended steps to optimize the click behavior in mobile web views while preserving the web view content.
Prerequisites
- Complete the Set up the web view guide.
Implementation
Follow these steps to optimize the click behavior in your WebView
instance:
Override
shouldOverrideUrlLoading()
on theWebViewClient
. This method is called when a URL is about to be loaded in the currentWebView
.Determine whether to override the behavior of the click URL.
The code example checks if the current domain is different than the target domain. This is just one approach as the criteria you use could vary.
Decide whether to open the URL in an external browser, Android Custom Tabs, or within the existing web view. This guide shows how to open URLs navigating away from the site by launching Android Custom Tabs.
Code example
First add the androidx.browser
dependency to your module-level build.gradle
file, typically app/build.gradle
. This is required for Custom Tabs:
dependencies{
implementation'androidx.browser:browser:1.5.0'
}
The following code snippet shows how to implement shouldOverrideUrlLoading()
:
Java
publicclass MainActivityextendsAppCompatActivity{
privateWebViewwebView;
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
// ... Register the WebView.
webView=newWebView(this);
WebSettingswebSettings=webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(
newWebViewClient(){
// 1. Implement the web view click handler.
@Override
publicbooleanshouldOverrideUrlLoading(
WebViewview,
WebResourceRequestrequest){
// 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){
returnfalse;
}
// 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")){
Intentintent=newIntent(Intent.ACTION_VIEW,request.getUrl());
// If the URL cannot be opened, return early.
try{
MainActivity.this.startActivity(intent);
}catch(ActivityNotFoundExceptionexception){
Log.d("TAG","Failed to load URL with scheme:"+request.getUrl().getScheme());
}
returntrue;
}
StringcurrentDomain;
// If the current URL's host cannot be found, return early.
try{
currentDomain=newURI(view.getUrl()).toURL().getHost();
}catch(URISyntaxException|MalformedURLExceptionexception){
// Malformed URL.
returnfalse;
}
StringtargetDomain=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)){
returnfalse;
}
// 3. User is navigating away from the site, open the URL in
// Custom Tabs to preserve the state of the web view.
CustomTabsIntentintent=newCustomTabsIntent.Builder().build();
intent.launchUrl(MainActivity.this,request.getUrl());
returntrue;
}
});
}
}
Kotlin
classMainActivity:AppCompatActivity(){
privatelateinitvarwebView:WebView
overridefunonCreate(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
// ... Register the WebView.
webView.webViewClient=object:WebViewClient(){
// 1. Implement the web view click handler.
overridefunshouldOverrideUrlLoading(
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){
returnfalse
}
valcurrentDomain=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")){
valintent=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}")
}
returntrue
}
valtargetDomain=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)){
returnfalse
}
// 3. User is navigating away from the site, open the URL in
// Custom Tabs to preserve the state of the web view.
valcustomTabsIntent=CustomTabsIntent.Builder().build()
customTabsIntent.launchUrl(this@MainActivity,request.url)
returntrue
}
}
}
}
Test your page navigation
To test your page navigation changes, load
https://google.github.io/webview-ads/test/#click-behavior-tests
into your web view. Click each of the different link types to see how they behave in your app.
Here are some things to check:
- Each link opens the intended URL.
- When returning to the app, the test page's counter doesn't reset to zero to validate the page state was preserved.