Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Make Webview safer - some of the code based on recommendations in article
* Implements whitelisting on host name
public class SaferWebViewClient extends WebViewClient {
private String[] hostsWhitelist;
public SaferWebViewClient(String hostsWhitelsit){
this.hostsWhitelist = hostsWhitelist;
public WebResourceResponse shouldInterceptRequest(final WebView view, String url) {
if (isValidHost(url)) {
return super.shouldInterceptRequest(view, url);
} else {
return getWebResourceResponseFromString();
private WebResourceResponse getWebResourceResponseFromString() {
return getUtf8EncodedWebResourceResponse(new StringBufferInputStream("alert('!NO!')"));
private WebResourceResponse getUtf8EncodedWebResourceResponse(InputStream data) {
return new WebResourceResponse("text/css", "UTF-8", data);
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return isValidHost(url);
private boolean isValidHost(String url){
if (!TextUtils.isEmpty(url)) {
final String host = Uri.parse(url).getHost();
for (String whitelistedHost: hostsWhitelist){
if (whitelistedHost.equalsIgnoreCase(host)){
return true;
return false;
public class Util {
public static void disableRiskySettings(WebView webView){
//javascript could be a vector to exploit your applications
//default is off, but just in case. plugins could be a vector to exploit your applications process
//Should an attacker somehow find themselves in a position to inject script into a WebView, then they could exploit the opportunity to access local resources. This can be somewhat prevented by disabling local file system access. It is enabled by default. The Android WebSettings class can be used to disable local file system access via the public method setAllowFileAccess.
//This restricts the WebView to loading local resources from file:///android_asset (assets) and file:///android_res (resources).
//disable Geolocation API
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment