├── .gitignore ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle.kts ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── acsbendi │ │ └── requestinspectorwebview │ │ └── ExampleInstrumentedTest.kt │ ├── main │ └── java │ │ └── com │ │ └── acsbendi │ │ └── requestinspectorwebview │ │ ├── RequestInspectorJavaScriptInterface.kt │ │ ├── RequestInspectorOptions.kt │ │ ├── RequestInspectorWebViewClient.kt │ │ ├── WebViewRequest.kt │ │ └── WebViewRequestType.kt │ └── test │ └── java │ └── com │ └── acsbendi │ └── requestinspectorwebview │ └── ExampleUnitTest.kt ├── build.gradle.kts ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── jitpack.yml └── settings.gradle.kts /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | /.idea/navEditor.xml 9 | /.idea/assetWizardSettings.xml 10 | .idea 11 | .DS_Store 12 | /build 13 | /captures 14 | .externalNativeBuild 15 | .cxx 16 | local.properties 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2022 Bendegúz Ács 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Android Request Inspector WebView [![Release](https://jitpack.io/v/acsbendi/Android-Request-Inspector-WebView.svg)](https://jitpack.io/#acsbendi/Android-Request-Inspector-WebView) 2 | 3 | Inspect and intercept full HTTP requests (including all headers, cookies and body) sent from Android WebViews. 4 | 5 | This project is inspired by [android-post-webview](https://github.com/KeejOow/android-post-webview) and [request_data_webviewclient](https://github.com/KonstantinSchubert/request_data_webviewclient) and some code was taken from both projects. 6 | 7 | Installation 8 | === 9 | 10 | **Step 1.** Add the JitPack repository to your build file: 11 | 12 | ```gradle 13 | allprojects { 14 | repositories { 15 | maven { url 'https://jitpack.io' } 16 | } 17 | } 18 | ``` 19 | 20 | **Step 2.** Add the dependency 21 | 22 | ```gradle 23 | dependencies { 24 | implementation 'com.github.acsbendi:Android-Request-Inspector-WebView:1.0.12' 25 | } 26 | ``` 27 | 28 | Get the latest version on [JitPack](https://jitpack.io/#acsbendi/Android-Request-Inspector-WebView) 29 | 30 | Usage 31 | === 32 | 33 | To log the requests (default functionality): 34 | 35 | ```kotlin 36 | val webView = WebView(this) 37 | webView.webViewClient = RequestInspectorWebViewClient(webView) 38 | ``` 39 | 40 | To manually process requests: 41 | 42 | ```kotlin 43 | val webView = WebView(this) 44 | webView.webViewClient = object : RequestInspectorWebViewClient(webView) { 45 | override fun shouldInterceptRequest( 46 | view: WebView, 47 | webViewRequest: WebViewRequest 48 | ): WebResourceResponse? { 49 | TODO("handle request manually based on data from webViewRequest and return custom response") 50 | return super.shouldInterceptRequest(view, webViewRequest) 51 | } 52 | } 53 | ``` 54 | 55 | Known limitations 56 | === 57 | 58 | Detailed data (e.g. request body) is not available for requests sent from iframes as it's [not possible to execute JavaScript code in iframes in Android WebViews](https://stackoverflow.com/questions/47820169/android-webview-run-javascript-in-all-frames-including-iframes). One possible workaround to still inspect the requests sent from a specific iframe is to load its URL into a different `WebView` and attach `RequestInspectorWebViewClient` to that. 59 | 60 | Contributions 61 | === 62 | 63 | All feedback, PRs, and issues are welcome! 64 | 65 | License 66 | === 67 | The MIT License 68 | 69 | See [LICENSE](LICENSE) 70 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /app/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("com.android.library") 3 | kotlin("android") 4 | `maven-publish` 5 | } 6 | 7 | val currentVersion = "1.0.12" 8 | 9 | group = "com.acsbendi" 10 | version = currentVersion 11 | 12 | android { 13 | compileSdk = 31 14 | namespace = "com.acsbendi.requestinspectorwebview" 15 | 16 | defaultConfig { 17 | minSdk = 21 18 | targetSdk = 31 19 | 20 | version = currentVersion 21 | } 22 | 23 | buildTypes { 24 | getByName("release") { 25 | isMinifyEnabled = false 26 | proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro") 27 | } 28 | } 29 | 30 | compileOptions { 31 | sourceCompatibility = JavaVersion.VERSION_11 32 | targetCompatibility = JavaVersion.VERSION_11 33 | } 34 | 35 | publishing { 36 | singleVariant("release") { 37 | withSourcesJar() 38 | } 39 | } 40 | } 41 | 42 | publishing { 43 | publications { 44 | register("release") { 45 | groupId = group as String 46 | artifactId = "requestinspectorwebview" 47 | version = currentVersion 48 | 49 | afterEvaluate { 50 | from(components["release"]) 51 | } 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /app/src/androidTest/java/com/acsbendi/requestinspectorwebview/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.acsbendi.requestinspectorwebview 2 | 3 | import androidx.test.platform.app.InstrumentationRegistry 4 | import androidx.test.ext.junit.runners.AndroidJUnit4 5 | 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | import org.junit.Assert.* 10 | 11 | /** 12 | * Instrumented test, which will execute on an Android device. 13 | * 14 | * See [testing documentation](http://d.android.com/tools/testing). 15 | */ 16 | @RunWith(AndroidJUnit4::class) 17 | class ExampleInstrumentedTest { 18 | @Test 19 | fun useAppContext() { 20 | // Context of the app under test. 21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext 22 | assertEquals("com.acsbendi.requestinspectorwebview", appContext.packageName) 23 | } 24 | } -------------------------------------------------------------------------------- /app/src/main/java/com/acsbendi/requestinspectorwebview/RequestInspectorJavaScriptInterface.kt: -------------------------------------------------------------------------------- 1 | package com.acsbendi.requestinspectorwebview 2 | 3 | import android.util.Log 4 | import android.webkit.JavascriptInterface 5 | import android.webkit.WebView 6 | import org.intellij.lang.annotations.Language 7 | import org.json.JSONArray 8 | import org.json.JSONObject 9 | import java.net.URLEncoder 10 | import java.util.Locale 11 | 12 | internal class RequestInspectorJavaScriptInterface(webView: WebView) { 13 | 14 | init { 15 | webView.addJavascriptInterface(this, INTERFACE_NAME) 16 | } 17 | 18 | private val recordedRequests = ArrayList() 19 | 20 | fun findRecordedRequestForUrl(url: String): RecordedRequest? { 21 | return synchronized(recordedRequests) { 22 | // use findLast instead of find to find the last added query matching a URL - 23 | // they are included at the end of the list when written. 24 | recordedRequests.findLast { recordedRequest -> 25 | // Added search by exact URL to find the actual request body 26 | url == recordedRequest.url 27 | } ?: recordedRequests.findLast { recordedRequest -> 28 | // Previously, there was only a search by contains, and because of this, sometimes the wrong request body was found 29 | url.contains(recordedRequest.url) 30 | } 31 | } 32 | } 33 | 34 | data class RecordedRequest( 35 | val type: WebViewRequestType, 36 | val url: String, 37 | val method: String, 38 | val body: String, 39 | val formParameters: Map, 40 | val headers: Map, 41 | val trace: String, 42 | val enctype: String? 43 | ) 44 | 45 | @JavascriptInterface 46 | fun recordFormSubmission( 47 | url: String, 48 | method: String, 49 | formParameterList: String, 50 | headers: String, 51 | trace: String, 52 | enctype: String? 53 | ) { 54 | val formParameterJsonArray = JSONArray(formParameterList) 55 | val headerMap = getHeadersAsMap(headers) 56 | val formParameterMap = getFormParametersAsMap(formParameterJsonArray) 57 | 58 | val body = when (enctype) { 59 | "application/x-www-form-urlencoded" -> { 60 | headerMap["content-type"] = enctype 61 | getUrlEncodedFormBody(formParameterJsonArray) 62 | } 63 | 64 | "multipart/form-data" -> { 65 | headerMap["content-type"] = "multipart/form-data; boundary=$MULTIPART_FORM_BOUNDARY" 66 | getMultiPartFormBody(formParameterJsonArray) 67 | } 68 | 69 | "text/plain" -> { 70 | headerMap["content-type"] = enctype 71 | getPlainTextFormBody(formParameterJsonArray) 72 | } 73 | 74 | else -> { 75 | Log.e(LOG_TAG, "Incorrect encoding received from JavaScript: $enctype") 76 | "" 77 | } 78 | } 79 | 80 | Log.i(LOG_TAG, "Recorded form submission from JavaScript") 81 | addRecordedRequest( 82 | RecordedRequest( 83 | WebViewRequestType.FORM, 84 | url, 85 | method, 86 | body, 87 | formParameterMap, 88 | headerMap, 89 | trace, 90 | enctype 91 | ) 92 | ) 93 | } 94 | 95 | @JavascriptInterface 96 | fun recordXhr(url: String, method: String, body: String, headers: String, trace: String) { 97 | Log.i(LOG_TAG, "Recorded XHR from JavaScript") 98 | val headerMap = getHeadersAsMap(headers) 99 | addRecordedRequest( 100 | RecordedRequest( 101 | WebViewRequestType.XML_HTTP, 102 | url, 103 | method, 104 | body, 105 | mapOf(), 106 | headerMap, 107 | trace, 108 | null 109 | ) 110 | ) 111 | } 112 | 113 | @JavascriptInterface 114 | fun recordFetch(url: String, method: String, body: String, headers: String, trace: String) { 115 | Log.i(LOG_TAG, "Recorded fetch from JavaScript") 116 | val headerMap = getHeadersAsMap(headers) 117 | addRecordedRequest( 118 | RecordedRequest( 119 | WebViewRequestType.FETCH, 120 | url, 121 | method, 122 | body, 123 | mapOf(), 124 | headerMap, 125 | trace, 126 | null 127 | ) 128 | ) 129 | } 130 | 131 | private fun addRecordedRequest(recordedRequest: RecordedRequest) { 132 | synchronized(recordedRequests) { 133 | recordedRequests.add(recordedRequest) 134 | } 135 | } 136 | 137 | private fun getHeadersAsMap(headersString: String): MutableMap { 138 | val headersObject = JSONObject(headersString) 139 | val map = HashMap() 140 | for (key in headersObject.keys()) { 141 | val lowercaseHeader = key.lowercase(Locale.getDefault()) 142 | map[lowercaseHeader] = headersObject.getString(key) 143 | } 144 | return map 145 | } 146 | 147 | private fun getFormParametersAsMap(formParameterJsonArray: JSONArray): Map { 148 | val map = HashMap() 149 | repeat(formParameterJsonArray.length()) { i -> 150 | val formParameter = formParameterJsonArray.get(i) as JSONObject 151 | val name = formParameter.getString("name") 152 | val value = formParameter.optString("value") 153 | val checked = formParameter.optBoolean("checked") 154 | val type = formParameter.optString("type") 155 | if (!isExcludedFormParameter(type, checked)) { 156 | map[name] = value 157 | } 158 | } 159 | return map 160 | } 161 | 162 | 163 | private fun getUrlEncodedFormBody(formParameterJsonArray: JSONArray): String { 164 | val resultStringBuilder = StringBuilder() 165 | repeat(formParameterJsonArray.length()) { i -> 166 | val formParameter = formParameterJsonArray.get(i) as JSONObject 167 | val name = formParameter.getString("name") 168 | val value = formParameter.optString("value") 169 | val checked = formParameter.optBoolean("checked") 170 | val type = formParameter.optString("type") 171 | val encodedValue = URLEncoder.encode(value, "UTF-8") 172 | 173 | if (!isExcludedFormParameter(type, checked)) { 174 | if (i != 0) { 175 | resultStringBuilder.append("&") 176 | } 177 | resultStringBuilder.append(name) 178 | resultStringBuilder.append("=") 179 | resultStringBuilder.append(encodedValue) 180 | } 181 | 182 | 183 | } 184 | return resultStringBuilder.toString() 185 | } 186 | 187 | private fun getMultiPartFormBody(formParameterJsonArray: JSONArray): String { 188 | val resultStringBuilder = StringBuilder() 189 | repeat(formParameterJsonArray.length()) { i -> 190 | val formParameter = formParameterJsonArray.get(i) as JSONObject 191 | val name = formParameter.getString("name") 192 | val value = formParameter.optString("value") 193 | val checked = formParameter.optBoolean("checked") 194 | val type = formParameter.optString("type") 195 | 196 | if (!isExcludedFormParameter(type, checked)) { 197 | resultStringBuilder.append("--") 198 | resultStringBuilder.append(MULTIPART_FORM_BOUNDARY) 199 | resultStringBuilder.append("\n") 200 | resultStringBuilder.append("Content-Disposition: form-data; name=\"$name\"") 201 | resultStringBuilder.append("\n\n") 202 | resultStringBuilder.append(value) 203 | resultStringBuilder.append("\n") 204 | } 205 | 206 | } 207 | resultStringBuilder.append("--") 208 | resultStringBuilder.append(MULTIPART_FORM_BOUNDARY) 209 | resultStringBuilder.append("--") 210 | return resultStringBuilder.toString() 211 | } 212 | 213 | private fun getPlainTextFormBody(formParameterJsonArray: JSONArray): String { 214 | val resultStringBuilder = StringBuilder() 215 | repeat(formParameterJsonArray.length()) { i -> 216 | val formParameter = formParameterJsonArray.get(i) as JSONObject 217 | val name = formParameter.getString("name") 218 | val value = formParameter.optString("value") 219 | val checked = formParameter.optBoolean("checked") 220 | val type = formParameter.optString("type") 221 | 222 | if (!isExcludedFormParameter(type, checked)) { 223 | if (i != 0) { 224 | resultStringBuilder.append("\n") 225 | } 226 | resultStringBuilder.append(name) 227 | resultStringBuilder.append("=") 228 | resultStringBuilder.append(value) 229 | } 230 | 231 | } 232 | return resultStringBuilder.toString() 233 | } 234 | 235 | private fun isExcludedFormParameter(type: String, checked: Boolean): Boolean { 236 | return (type == "radio" || type == "checkbox") && !checked 237 | } 238 | 239 | companion object { 240 | private const val LOG_TAG = "RequestInspectorJs" 241 | private const val MULTIPART_FORM_BOUNDARY = "----WebKitFormBoundaryU7CgQs9WnqlZYKs6" 242 | private const val INTERFACE_NAME = "RequestInspection" 243 | 244 | @Language("JS") 245 | private const val JAVASCRIPT_INTERCEPTION_CODE = """ 246 | function getFullUrl(url) { 247 | if (url.startsWith("/")) { 248 | return location.protocol + '//' + location.host + url; 249 | } else { 250 | return url; 251 | } 252 | } 253 | 254 | function recordFormSubmission(form) { 255 | var jsonArr = []; 256 | for (i = 0; i < form.elements.length; i++) { 257 | var parName = form.elements[i].name; 258 | var parValue = form.elements[i].value; 259 | var parType = form.elements[i].type; 260 | var parChecked = form.elements[i].checked; 261 | var parId = form.elements[i].id; 262 | 263 | jsonArr.push({ 264 | name: parName, 265 | value: parValue, 266 | type: parType, 267 | checked:parChecked, 268 | id:parId 269 | }); 270 | } 271 | 272 | const path = form.attributes['action'] === undefined ? "/" : form.attributes['action'].nodeValue; 273 | const method = form.attributes['method'] === undefined ? "GET" : form.attributes['method'].nodeValue; 274 | const url = getFullUrl(path); 275 | const encType = form.attributes['enctype'] === undefined ? "application/x-www-form-urlencoded" : form.attributes['enctype'].nodeValue; 276 | const err = new Error(); 277 | $INTERFACE_NAME.recordFormSubmission( 278 | url, 279 | method, 280 | JSON.stringify(jsonArr), 281 | "{}", 282 | err.stack, 283 | encType 284 | ); 285 | } 286 | 287 | function handleFormSubmission(e) { 288 | const form = e ? e.target : this; 289 | recordFormSubmission(form); 290 | form._submit(); 291 | } 292 | 293 | HTMLFormElement.prototype._submit = HTMLFormElement.prototype.submit; 294 | HTMLFormElement.prototype.submit = handleFormSubmission; 295 | window.addEventListener('submit', function (submitEvent) { 296 | const form = submitEvent ? submitEvent.target : this; 297 | recordFormSubmission(form); 298 | }, true); 299 | 300 | let lastXmlhttpRequestPrototypeMethod = null; 301 | let xmlhttpRequestHeaders = {}; 302 | let xmlhttpRequestUrl = null; 303 | XMLHttpRequest.prototype._open = XMLHttpRequest.prototype.open; 304 | XMLHttpRequest.prototype.open = function (method, url, async, user, password) { 305 | lastXmlhttpRequestPrototypeMethod = method; 306 | xmlhttpRequestUrl = url; 307 | const asyncWithDefault = async === undefined ? true : async; 308 | this._open(method, url, asyncWithDefault, user, password); 309 | }; 310 | XMLHttpRequest.prototype._setRequestHeader = XMLHttpRequest.prototype.setRequestHeader; 311 | XMLHttpRequest.prototype.setRequestHeader = function (header, value) { 312 | xmlhttpRequestHeaders[header] = value; 313 | this._setRequestHeader(header, value); 314 | }; 315 | XMLHttpRequest.prototype._send = XMLHttpRequest.prototype.send; 316 | XMLHttpRequest.prototype.send = function (body) { 317 | const err = new Error(); 318 | const url = getFullUrl(xmlhttpRequestUrl); 319 | $INTERFACE_NAME.recordXhr( 320 | url, 321 | lastXmlhttpRequestPrototypeMethod, 322 | body || "", 323 | JSON.stringify(xmlhttpRequestHeaders), 324 | err.stack 325 | ); 326 | lastXmlhttpRequestPrototypeMethod = null; 327 | xmlhttpRequestUrl = null; 328 | xmlhttpRequestHeaders = {}; 329 | this._send(body); 330 | }; 331 | 332 | window._fetch = window.fetch; 333 | window.fetch = function () { 334 | const firstArgument = arguments[0]; 335 | let url; 336 | let method; 337 | let body; 338 | let headers; 339 | if (typeof firstArgument === 'string') { 340 | url = firstArgument; 341 | method = arguments[1] && 'method' in arguments[1] ? arguments[1]['method'] : "GET"; 342 | body = arguments[1] && 'body' in arguments[1] ? arguments[1]['body'] : ""; 343 | headers = JSON.stringify(arguments[1] && 'headers' in arguments[1] ? arguments[1]['headers'] : {}); 344 | } else { 345 | // Request object 346 | url = firstArgument.url; 347 | method = firstArgument.method; 348 | body = firstArgument.body; 349 | headers = JSON.stringify(Object.fromEntries(firstArgument.headers.entries())); 350 | } 351 | const fullUrl = getFullUrl(url); 352 | const err = new Error(); 353 | $INTERFACE_NAME.recordFetch(fullUrl, method, body, headers, err.stack); 354 | return window._fetch.apply(this, arguments); 355 | } 356 | """ 357 | 358 | fun enabledRequestInspection(webView: WebView, extraJavaScriptToInject: String) { 359 | webView.evaluateJavascript( 360 | "javascript: $JAVASCRIPT_INTERCEPTION_CODE\n$extraJavaScriptToInject", 361 | null 362 | ) 363 | } 364 | } 365 | } 366 | -------------------------------------------------------------------------------- /app/src/main/java/com/acsbendi/requestinspectorwebview/RequestInspectorOptions.kt: -------------------------------------------------------------------------------- 1 | package com.acsbendi.requestinspectorwebview 2 | 3 | data class RequestInspectorOptions( 4 | val extraJavaScriptToInject: String = "" 5 | ) 6 | -------------------------------------------------------------------------------- /app/src/main/java/com/acsbendi/requestinspectorwebview/RequestInspectorWebViewClient.kt: -------------------------------------------------------------------------------- 1 | package com.acsbendi.requestinspectorwebview 2 | 3 | import android.annotation.SuppressLint 4 | import android.graphics.Bitmap 5 | import android.util.Log 6 | import android.webkit.WebResourceRequest 7 | import android.webkit.WebResourceResponse 8 | import android.webkit.WebView 9 | import android.webkit.WebViewClient 10 | 11 | @SuppressLint("SetJavaScriptEnabled") 12 | open class RequestInspectorWebViewClient @JvmOverloads constructor( 13 | webView: WebView, 14 | private val options: RequestInspectorOptions = RequestInspectorOptions() 15 | ) : WebViewClient() { 16 | 17 | private val interceptionJavascriptInterface = RequestInspectorJavaScriptInterface(webView) 18 | 19 | init { 20 | val webSettings = webView.settings 21 | webSettings.javaScriptEnabled = true 22 | webSettings.domStorageEnabled = true 23 | } 24 | 25 | final override fun shouldInterceptRequest( 26 | view: WebView, 27 | request: WebResourceRequest 28 | ): WebResourceResponse? { 29 | val recordedRequest = interceptionJavascriptInterface.findRecordedRequestForUrl( 30 | request.url.toString() 31 | ) 32 | val webViewRequest = WebViewRequest.create(request, recordedRequest) 33 | return shouldInterceptRequest(view, webViewRequest) 34 | } 35 | 36 | open fun shouldInterceptRequest( 37 | view: WebView, 38 | webViewRequest: WebViewRequest 39 | ): WebResourceResponse? { 40 | logWebViewRequest(webViewRequest) 41 | return null 42 | } 43 | 44 | @Suppress("MemberVisibilityCanBePrivate") 45 | protected fun logWebViewRequest(webViewRequest: WebViewRequest) { 46 | Log.i(LOG_TAG, "Sending request from WebView: $webViewRequest") 47 | } 48 | 49 | override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) { 50 | Log.i(LOG_TAG, "Page started loading, enabling request inspection. URL: $url") 51 | RequestInspectorJavaScriptInterface.enabledRequestInspection( 52 | view, 53 | options.extraJavaScriptToInject 54 | ) 55 | super.onPageStarted(view, url, favicon) 56 | } 57 | 58 | companion object { 59 | private const val LOG_TAG = "RequestInspectorWebView" 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /app/src/main/java/com/acsbendi/requestinspectorwebview/WebViewRequest.kt: -------------------------------------------------------------------------------- 1 | package com.acsbendi.requestinspectorwebview 2 | 3 | import android.os.Build 4 | import android.webkit.CookieManager 5 | import android.webkit.WebResourceRequest 6 | 7 | data class WebViewRequest( 8 | val type: WebViewRequestType, 9 | val url: String, 10 | val method: String, 11 | val body: String, 12 | val formParameters: Map, 13 | val headers: Map, 14 | val trace: String, 15 | val enctype: String?, 16 | val isForMainFrame: Boolean, 17 | val isRedirect: Boolean, 18 | val hasGesture: Boolean 19 | ) { 20 | override fun toString(): String { 21 | val headersString = headers.entries.joinToString("\n", "\n") { (key, value) -> 22 | " $key: $value" 23 | } 24 | val formParametersString = formParameters.entries.joinToString("\n", "\n") { (key, value) -> 25 | " $key: $value" 26 | } 27 | val traceWithIndent = 28 | trace 29 | .lines() 30 | // Remove the first line that always says "Error" 31 | .drop(1) 32 | .joinToString("\n", "\n") { 33 | " ${it.trim()}" 34 | } 35 | return """ 36 | Type: $type 37 | URL: $url 38 | Method: $method 39 | Body: $body 40 | Headers: $headersString 41 | FormParameters: $formParametersString 42 | Trace: $traceWithIndent 43 | Encoding type (form submissions only): $enctype 44 | Is for main frame? $isForMainFrame 45 | Is redirect? $isRedirect 46 | Has gesture? $hasGesture 47 | """ 48 | } 49 | 50 | companion object { 51 | internal fun create( 52 | webResourceRequest: WebResourceRequest, 53 | recordedRequest: RequestInspectorJavaScriptInterface.RecordedRequest? 54 | ): WebViewRequest { 55 | val type = recordedRequest?.type ?: WebViewRequestType.HTML 56 | val url = webResourceRequest.url.toString() 57 | val cookies = CookieManager.getInstance().getCookie(url) ?: "" 58 | val headers = HashMap() 59 | headers["cookie"] = cookies 60 | if (recordedRequest != null) { 61 | val recordedHeadersInLowercase = recordedRequest.headers.mapKeys { (key, _) -> 62 | key.lowercase() 63 | } 64 | headers.putAll(recordedHeadersInLowercase) 65 | } 66 | val requestHeadersInLowercase = webResourceRequest.requestHeaders.mapKeys { (key, _) -> 67 | key.lowercase() 68 | } 69 | headers.putAll(requestHeadersInLowercase) 70 | 71 | val isRedirect = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 72 | webResourceRequest.isRedirect 73 | } else { 74 | false 75 | } 76 | return WebViewRequest( 77 | type = type, 78 | url = url, 79 | method = webResourceRequest.method, 80 | body = recordedRequest?.body ?: "", 81 | headers = headers, 82 | trace = recordedRequest?.trace ?: "", 83 | enctype = recordedRequest?.enctype, 84 | isForMainFrame = webResourceRequest.isForMainFrame, 85 | isRedirect = isRedirect, 86 | hasGesture = webResourceRequest.hasGesture(), 87 | formParameters = recordedRequest?.formParameters ?: mapOf() 88 | ) 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /app/src/main/java/com/acsbendi/requestinspectorwebview/WebViewRequestType.kt: -------------------------------------------------------------------------------- 1 | package com.acsbendi.requestinspectorwebview 2 | 3 | enum class WebViewRequestType { 4 | FETCH, XML_HTTP, FORM, HTML 5 | } 6 | -------------------------------------------------------------------------------- /app/src/test/java/com/acsbendi/requestinspectorwebview/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package com.acsbendi.requestinspectorwebview 2 | 3 | import org.junit.Test 4 | 5 | import org.junit.Assert.* 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * See [testing documentation](http://d.android.com/tools/testing). 11 | */ 12 | class ExampleUnitTest { 13 | @Test 14 | fun addition_isCorrect() { 15 | assertEquals(4, 2 + 2) 16 | } 17 | } -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | google() 6 | mavenCentral() 7 | } 8 | dependencies { 9 | classpath("com.android.tools.build:gradle:8.4.0") 10 | classpath(kotlin("gradle-plugin", version = "1.6.21")) 11 | 12 | // NOTE: Do not place your application dependencies here; they belong 13 | // in the individual module build.gradle files 14 | } 15 | } 16 | 17 | tasks.register("clean", Delete::class) { 18 | delete(rootProject.buildDir) 19 | } 20 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app"s APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Kotlin code style for this project: "official" or "obsolete": 19 | kotlin.code.style=official 20 | # Enables namespacing of each library's R class so that its R class includes only the 21 | # resources declared in the library itself and none from the library's dependencies, 22 | # thereby reducing the size of the R class for that library 23 | android.nonTransitiveRClass=true -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/acsbendi/Android-Request-Inspector-WebView/1b6ad0a61f0a132bbf2c2cc2b4acbafec7635b7e/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Oct 23 21:21:13 CEST 2024 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip 5 | networkTimeout=10000 6 | validateDistributionUrl=true 7 | zipStoreBase=GRADLE_USER_HOME 8 | zipStorePath=wrapper/dists 9 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /jitpack.yml: -------------------------------------------------------------------------------- 1 | jdk: 2 | - openjdk17 3 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | gradlePluginPortal() 4 | google() 5 | mavenCentral() 6 | } 7 | } 8 | dependencyResolutionManagement { 9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) 10 | repositories { 11 | google() 12 | mavenCentral() 13 | } 14 | } 15 | rootProject.name = "Request Inspector WebView" 16 | include(":app") 17 | --------------------------------------------------------------------------------