Created
August 5, 2018 10:57
-
-
Save vorobeij/767697d333f56ad6401c131b8f63f82b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package au.sj.sparrow.adblockwebview | |
import android.webkit.WebResourceRequest | |
import android.webkit.WebResourceResponse | |
import android.webkit.WebView | |
import android.webkit.WebViewClient | |
import okhttp3.HttpUrl | |
import java.io.ByteArrayInputStream | |
/** | |
* Created by vorobei on 04/08/2018 | |
* @param blacklist - hash set of domains we want to block | |
*/ | |
class AdBlockWebViewClient(var blacklist: HashSet<String> = HashSet()) : WebViewClient() { | |
private val loadedUrls = HashMap<String, Boolean>() | |
override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? { | |
val ad: Boolean | |
val url = request?.url.toString() | |
if (!loadedUrls.containsKey(url)) { | |
ad = isAd(url) | |
loadedUrls[url] = ad | |
} else { | |
ad = loadedUrls[url] ?: false | |
} | |
return if (ad) createEmptyResourse() | |
else super.shouldInterceptRequest(view, request) | |
} | |
private fun createEmptyResourse(): WebResourceResponse { | |
return WebResourceResponse("text/plain", "utf-8", ByteArrayInputStream("".toByteArray())) | |
} | |
private fun isAd(url: String): Boolean { | |
val httpUrl = HttpUrl.parse(url) | |
return isAdHost(httpUrl?.host() ?: "") | |
} | |
private fun isAdHost(host: String): Boolean { | |
if (host.isEmpty()) return false | |
val index = host.indexOf(".") | |
return index >= 0 && (blacklist.contains(host) || | |
index + 1 < host.length && isAdHost(host.substring(index + 1))) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment