androidandroid-activityandroid-webview

Android: Limit webview to a number of URLs


In my application, I want to limit the URL to a number of domains. For example, if I want to limit it to one domain, this works:

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if(Uri.parse(url).getHost().endsWith("stackoverflow.com")) {
        return false;
    }

    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    view.getContext().startActivity(intent);
    return true;
}

So how do I alter this line:

if(Uri.parse(url).getHost().endsWith("stackoverflow.com"))

To whitelist a number of URLs, like:

stackoverflow.com
stackexchange.com
google.com

Solution

  • I think the fastest way is to keep a list of your allowed hosts.

    List<String> allowedHosts = Arrays.asList("stackoverflow.com", "stackexchange.com", "google.com");
    
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        String host = Uri.parse(url).getHost();
        if (allowedHosts.contains(host) {
            return false;
        }
    
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        view.getContext().startActivity(intent);
        return true;
    }