Last active
December 27, 2022 22:25
-
-
Save joshuatz/e801edbe9f545ebddb2352f2d1941db3 to your computer and use it in GitHub Desktop.
Example of how to intercept and block request with Android WebView
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 com.joshuatz.webviewblock | |
import android.os.Bundle | |
import android.util.Log | |
import android.webkit.* | |
import androidx.appcompat.app.AppCompatActivity | |
// Leave off www. | |
val BannedDomains: Array<String> = arrayOf("facebook.com", "connect.facebook.net") | |
val BannedUrlPatterns: Array<Regex> = arrayOf(Regex("\\.taboola\\.")) | |
class MainActivity : AppCompatActivity() { | |
private var webViewInstance: WebView? = null | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
val webView: WebView = findViewById(R.id.mainWebView) | |
webViewInstance = webView | |
webView.webViewClient = object : WebViewClient() { | |
override fun shouldInterceptRequest( | |
view: WebView, | |
request: WebResourceRequest | |
): WebResourceResponse? { | |
val shouldBlock = filterNetworkRequests(webView, request); | |
if (shouldBlock) { | |
return WebResourceResponse("text/javascript", "UTF-8", null) | |
} | |
return null | |
} | |
override fun shouldOverrideUrlLoading( | |
view: WebView, | |
request: WebResourceRequest | |
): Boolean { | |
return filterNetworkRequests(view, request) | |
} | |
} | |
webView.webChromeClient = object : WebChromeClient() { | |
// There are overrideable methods in here that we could hook into, | |
// but we don't actually need them for network request interception | |
} | |
webView.loadUrl("https://joshuatz.com") | |
} | |
/** | |
* This is our re-usable function that can be called by both `shouldOverrideUrlLoading` and | |
* by `shouldInterceptRequest` | |
*/ | |
fun filterNetworkRequests(view: WebView, request: WebResourceRequest): Boolean { | |
// By default, let all requests pass through | |
var shouldBlock = false; | |
val reqUri = request.url | |
val reqUrl = reqUri.toString() | |
if (BannedDomains.contains(reqUri.host?.replace("www.", ""))) { | |
shouldBlock = true | |
} | |
for (bannedPattern in BannedUrlPatterns) { | |
if (!shouldBlock) { | |
shouldBlock = bannedPattern.containsMatchIn(reqUrl) | |
} | |
} | |
return shouldBlock | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment