How do you troubleshoot WebView redirect errors on Android and iOS? Identify whether the failure involves a standard HTTPS navigation, a custom URL scheme, an Android intent:// URI, or a new-window request, then inspect the navigation through Chrome DevTools or Safari Web Inspector and trace the corresponding native delegate (shouldOverrideUrlLoading, onCreateWindow, decidePolicyForNavigationAction, or createWebViewWith). Verify target-app resolution, URI allowlists, frame and user-interaction policies, and fallback routing to isolate container-level errors from operating-system dispatch failures.
A WebView redirection error occurs when an embedded Android Chromium WebView or iOS WebKit WKWebView fails to route a navigation request to its intended destination. Typical causes include unsupported custom URL schemes, unhandled
target="_blank"requests, missing package visibility declarations, and rejected or looping fallback redirects.
Why Do Embedded Android WebView and iOS WKWebView Containers Drop Redirects

When debugging redirection failures, engineering teams must separate WebView engine behavior (how Chromium or WebKit parses URLs, frame targets, and popup events) from host application policy (how the application-supplied WebViewClient, WebChromeClient, WKNavigationDelegate, or WKUIDelegate evaluates user interaction types, allowlists, and external app handoffs). Standalone browsers include built-in URI dispatchers and link-handoff handlers, whereas android.webkit.WebView and Apple’s WKWebView are embedded rendering components that expect standard http:// or https:// network responses by default.
When a web page triggers a custom scheme (such as myapp://product/42) or an Android intent:// link without an active delegate override, default container behavior diverges across platforms:
- Android Chromium WebView: Per the Android
WebViewClientspecification, if no customWebViewClientis assigned, WebView may ask the Activity Manager to resolve the URL through available system handlers. When a customWebViewClientis assigned andshouldOverrideUrlLoadingreturnsfalsefor an unsupported custom scheme, WebView continues loading it inside Chromium and rendersnet::ERR_UNKNOWN_URL_SCHEME. - iOS WebKit WKWebView: WebKit rejects non-HTTP schemes internally and aborts the navigation unless the host’s
WKNavigationDelegateintercepts the request and forwards it toUIApplication, often failing silently or firingNSURLErrorUnsupportedURL.
Note also that Apple’s Promoting Apps with Smart App Banners is a Safari support feature designed for standalone Safari browsing rather than an embedded WKWebView navigation API, and should be evaluated separately from in-app custom URL scheme redirections.
At a Glance
- Separate Engine Behavior from Host Policy: Isolate whether a navigation failed inside the web engine (Chromium/WebKit), inside native delegate overrides, or at the OS package-resolution boundary.
- Inspect Live Redirects Before Coding: Use Chrome DevTools (
chrome://inspect) and Safari Web Inspector (isInspectable = true) to capture 3xx redirect chains,targetFramestates, and gesture flags. - Enforce Platform-Appropriate URI & Intent Validation: On Android, bind custom schemes and
intent://targets 1-to-1 to verified packages viaIntentSanitizerwithout webpage-supplied task flags; on iOS, validate full custom URI structures (relying on Universal Links where verified app-to-domain identity is required), and reject duplicate query keys on both platforms. - Apply Defense-in-Depth for Popups & Race Conditions: Confine Android popup session state strictly to the UI thread while understanding callback boundaries across
shouldInterceptRequestandshouldOverrideUrlLoading, and separate pure policy checks from external dispatch side effects in iOSWKWebViewusing action-level deduplication and navigation generation tokens.
Common Causes and Verification Steps for WebView Redirection Errors
Mapping Observed Client Errors to Underlying Container Failure Mechanisms
Use the diagnostic matrix below to map observed WebView symptoms to common platform root causes, verification steps, and targeted remediations:
| Observed Symptom or Error | Target Platform | Common Root Cause | Diagnostic Verification Step | Targeted Remediation |
|---|---|---|---|---|
WebView displays net::ERR_UNKNOWN_URL_SCHEME |
Android WebView | Custom WebViewClient returns false or lacks scheme allowlist |
Inspect request.url in shouldOverrideUrlLoading |
Intercept allowlisted URIs and dispatch 1-to-1 package-bound Intent.ACTION_VIEW |
| Silent hang when tapping a custom scheme link | iOS WKWebView | WebKit aborts non-HTTP URI when WKNavigationDelegate returns .allow |
Log navigationAction.request.url in decidePolicyForNavigationAction |
Route validated schemes via UIApplication.shared.open and pass .cancel |
target="_blank" replaces current page in WebView |
Android WebView | setSupportMultipleWindows(false) treats new windows as top-level loads |
Check webView.settings.supportMultipleWindows() |
Enable setSupportMultipleWindows(true) only if separate popup containers are needed |
target="_blank" does nothing or drops OAuth 302 redirects |
Android WebView | onCreateWindow is missing, or child client blocks isRedirect hops lacking hasGesture() |
Check onCreateWindow, request.isRedirect, and shouldInterceptRequest logs |
Attach a view-hosted popup WebView with UI-thread session state and bounded isRedirect hops |
Link with target="_blank" or window.open() does nothing |
iOS WKWebView | New-window navigation sets targetFrame == nil and requires WKUIDelegate |
Check navigationAction.targetFrame == nil |
Detect targetFrame == nil in decidePolicyForNavigationAction and handle via WKUIDelegate |
| Target app is installed, yet fallback page opens | Android 11+ (targetSdk >= 30) |
Missing <queries> declarations cause resolveActivity() or queryIntentActivities() to return incomplete results for invisible packages |
Add application-level logging around resolveActivity() and inspect output via adb logcat |
Declare <queries> intents if pre-checking, or invoke startActivity directly with ActivityNotFoundException catch |
| JavaScript timer redirect fails to open external app | iOS / Android | Automated script redirection lacks a user interaction signal | Check request.hasGesture() (Android) or navigationType (iOS) |
Bind redirections to direct user taps and define an explicit host gesture policy |
Universal Link loads inside WKWebView instead of target app |
iOS WKWebView | Browsing context, domain relationship, or JS navigation keeps load in WebKit | Check navigationType and host in decidePolicyForNavigationAction |
Call UIApplication.shared.open with .universalLinksOnly: true for allowed external hosts |
Five-Minute WebView Redirect Quick-Triage Checklist
- Step 1: Check Protocol Scheme in DevTools: Verify whether the page emitted an
https://, custom scheme, orintent://URI and confirm it was not blocked by Content Security Policy (CSP). - Step 2: Inspect Frame Hierarchy: Check whether the trigger originated inside a third-party
<iframe>(!isMainFrame). Host applications may intentionally block external-app launches initiated from third-party iframes. - Step 3: Distinguish Redirects from Timers: Check whether a non-gesture navigation is an authorized HTTP 3xx server redirect (
request.isRedirecton Android) versus an unprompted JavaScript timer. - Step 4: Check New-Window Triggers: Confirm whether
target="_blank"orwindow.open()created a new-window request (targetFrame == nilon iOS oronCreateWindowon Android). - Step 5: Verify OS Package Resolution: For apps targeting API 30+ on Android 11+, confirm whether pre-flight
resolveActivity()calls are failing due to missing<queries>declarations.
The following diagnostic workflow illustrates the sequential triage path for isolating container redirection failures:
[WebView Navigation Failure]
│
▼
[Inspect URL + Network + Console via Chrome DevTools / Safari Web Inspector]
│
▼
[Identify Navigation Source]
│
├── App loadUrl() or HTTP POST
│ │
│ └── shouldOverrideUrlLoading is NOT invoked; inspect host-side call path
│
├── target="_blank" or window.open()
│ │
│ ├── Android (multiple-windows=false) ──> Replaces current WebView page
│ ├── Android (multiple-windows=true) ──> Inspect onCreateWindow + shouldInterceptRequest
│ └── iOS (targetFrame == nil) ──> Inspect WKNavigationDelegate + WKUIDelegate
│
├── HTTP / HTTPS Navigation
│ │
│ └── Inspect Host + Port Allowlist, 3xx Redirects, Universal Link, or App Link matching
│
└── Custom Scheme or Chrome intent://
│
├── Evaluate User Interaction + Main Frame policy
├── Verify Full URI Structure (Scheme, Host, Port, Path, No Duplicate Query Keys)
├── Sanitize Intent (Reject Explicit Components, Verify 1-to-1 Package, Zero Webpage Flags)
├── Check Target-App Resolution (<queries> / ActivityNotFoundException)
└── Validate Fallback Path + Query Allowlist + Monotonic Chain Guard (elapsedRealtime)
How to Inspect WebView Navigation Events Using Remote Debugging Tools
Enabling Remote Debugging via Chrome DevTools and ADB Logcat on Android
Before modifying native delegates, verify whether the loaded web page emits the expected redirect. Per the Android Chrome DevTools remote debugging guide, explicitly enable remote WebView debugging in development builds by inspecting ApplicationInfo.FLAG_DEBUGGABLE and invoking WebView.setWebContentsDebuggingEnabled(true). Never ship debugging enabled in production releases:
// Android - Enable WebView debugging exclusively in debuggable builds
if (applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0) {
WebView.setWebContentsDebuggingEnabled(true)
}
Connect the device via USB, open chrome://inspect/#devices in desktop Chrome, and monitor the Network tab with Preserve log checked. Simultaneously filter native runtime logs via adb logcat to capture ActivityNotFoundException, SecurityException, or custom wrapper logs. Note that deprecation warnings for the legacy shouldOverrideUrlLoading(WebView, String) signature appear during Android Studio / Gradle compilation rather than in runtime adb logcat:
# Terminal - Filter logcat for custom WebView tags and ActivityTaskManager intent resolution
adb logcat -s "WebViewDebug" "ActivityTaskManager" "PackageManager"
Configuring isInspectable and Attaching Safari Web Inspector and Xcode Console on iOS
Beginning with iOS 16.4 and macOS 13.3, Apple requires applications to opt in via WKWebView.isInspectable, which defaults to false. Enable webView.isInspectable = true inside #if DEBUG blocks:
// iOS - Enable Safari Web Inspector opt-in on iOS 16.4+ debug builds
#if DEBUG
if #available(iOS 16.4, *) {
webView.isInspectable = true
}
#endif
On the physical iOS device, navigate to Settings > Apps > Safari > Advanced (on older iOS releases, Settings > Safari > Advanced) and enable Web Inspector. Connect via USB, open desktop Safari’s Develop menu, and monitor Xcode Console simultaneously for native decidePolicyForNavigationAction, createWebViewWith, and UIApplication.shared.open completion output.

Resolving Silent New Window Drops and Missing User Gestures in iOS WKWebView
Separating Policy Evaluation from Side Effects Across WKNavigationDelegate and WKUIDelegate
When a web link specifies target="_blank" or window.open(), WebKit creates a new-window navigation request where navigationAction.targetFrame is nil and involves both WKNavigationDelegate and WKUIDelegate. If the host app does not implement webView(_:createWebViewWithConfiguration:for:windowFeatures:), WebKit cannot spawn a secondary WebView, and navigations may appear to fail silently.
To prevent duplicate external app launches or double-incremented generation tokens when both delegates inspect a request, separate pure policy evaluation (evaluateNavigationPolicy) from execution side effects, and deduplicate by the specific WKNavigationAction instance (ObjectIdentifier(navigationAction)) rather than relying purely on a coarse time threshold that could suppress intentional rapid repeat clicks by a user. Evaluate navigationAction.targetFrame == nil directly in decidePolicyForNavigationAction: if the evaluation returns an external handoff plan, execute it once (recording the WKNavigationAction identifier) and pass .cancel; if it returns .allowInWebView for an allowlisted popup URL, pass .allow so createWebViewWith loads the popup safely. Always verify exact delegate callback ordering on target iOS versions.
Universal Link Context, Async Race Safety, and Custom Scheme Identity
Universal Link handoff depends on source browsing context, domain relationship, and Associated Domains configuration (verified via the target server’s apple-app-site-association file). Apple’s technical note TN3155: Debugging universal links documents how same-domain navigation in Safari favors staying in the browser, whereas distinct subdomains alter eligibility. Always test Associated Domains behavior on target iOS releases inside WKWebView.
When calling UIApplication.shared.open(url, options: [.universalLinksOnly: true]), guard against asynchronous navigation race conditions: if a user initiates any subsequent main-frame navigation attempt while the system processes the Universal Link handoff, an unguarded completion handler returning false could overwrite the user’s newer navigation state. Increment a monotonic activeNavigationGeneration token on every new main-frame navigation evaluation (including blocked or redirected attempts) so any pending prior asynchronous fallback is invalidated immediately, and verify self.activeNavigationGeneration == requestGeneration alongside self.isViewLoaded && self.view.window != nil before reloading fallback URLs.
Observe two strict security boundaries:
WKNavigationTypeClassification: Per Apple’sWKNavigationTypedocumentation,formSubmittedrepresents a request to submit a form rather than a link tap, and page scripts can submit forms programmatically. Restrict external app handoffs to WebKit-classified.linkActivatedevents combined withsourceFrame.isMainFrameand full URI allowlists, rather than treating.linkActivatedas an isolated cryptographic gesture token.- Custom Scheme Uniqueness & Parameter Pollution: Per Apple’s guide on Defining a Custom URL Scheme for Your App, multiple apps can claim the same custom scheme.
isAllowedCustomURL(_:)validates URI structure (scheme, host, default portnil, path pattern, no userinfo/fragment, and rejecting duplicate query keys), not target Bundle ID identity. Use domain-verified Universal Links whenever app identity binding is required.
Reference Architecture Disclaimer: The following implementation is a defensive reference architecture. Validate API availability, delegate ordering, and lifecycle behavior against the exact AndroidX and iOS versions used by your application.
// iOS - WebViewContainerController.swift
// Reference architecture: compile and test against your specific project targets (iOS 15.0–18.0)
import UIKit
import WebKit
final class WebViewContainerController: UIViewController, WKNavigationDelegate, WKUIDelegate {
private enum NavigationPlan: Equatable {
case allowInWebView
case launchCustomScheme(URL)
case attemptUniversalLink(URL)
case block
}
private var webView: WKWebView!
// Explicit allowlist for external custom URL schemes, hosts, and query keys
private let allowedCustomSchemes: Set<String> = ["myapp", "partnerapp"]
private let allowedCustomHosts: Set<String> = ["open", "product", "promo"]
private let allowedCustomQueryKeys: Set<String> = ["id", "ref", "promo"]
// Explicit allowlist for HTTPS hosts permitted inside the primary WebView container
private let allowedWebHosts: Set<String> = [
"example.com",
"m.example.com",
"links.example.com"
]
// Isolated allowlists specifically for child popup windows (target="_blank")
private let allowedPopupHosts: Set<String> = ["example.com", "auth.example.com"]
private let allowedPopupPathPrefixes: [String] = ["/oauth", "/popup", "/window"]
// External Universal Link hosts that attempt native app handoff on link activation
private let externalUniversalLinkHosts: Set<String> = ["links.example.com"]
// Monotonic navigation generation token incremented on every new main-frame navigation attempt
private var activeNavigationGeneration: UInt64 = 0
// Action-level deduplication preventing duplicate dispatches for the same WKNavigationAction
private var dispatchedActionIDs: [ObjectIdentifier] = []
private let maxTrackedActionIDs = 16
// Monotonic-uptime TTL-bounded bypass cache keyed by normalized Universal Link key
private var bypassedUniversalLinkKeys: [String: TimeInterval] = [:]
private let maxBypassedKeys = 10
private let bypassTTLSeconds: TimeInterval = 300
// Adapt significant query keys to match your application's actual routing parameters
private let significantLoopQueryKeys: Set<String> = ["id"]
override func viewDidLoad() {
super.viewDidLoad()
let configuration = WKWebViewConfiguration()
webView = WKWebView(frame: view.bounds, configuration: configuration)
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
webView.navigationDelegate = self
webView.uiDelegate = self
#if DEBUG
if #available(iOS 16.4, *) {
webView.isInspectable = true
}
#endif
view.addSubview(webView)
}
// MARK: - WKNavigationDelegate
func webView(
_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
) {
guard let url = navigationAction.request.url else {
decisionHandler(.cancel)
return
}
let isMainFrame = navigationAction.sourceFrame.isMainFrame
let isNewWindow = (navigationAction.targetFrame == nil)
// Increment generation token on every main-frame navigation attempt (including blocked attempts)
// so any pending prior asynchronous Universal Link fallback is invalidated immediately.
if isMainFrame && !isNewWindow {
activeNavigationGeneration &+= 1
}
let requestGeneration = activeNavigationGeneration
let plan = evaluateNavigationPolicy(
url: url,
navigationType: navigationAction.navigationType,
isMainFrame: isMainFrame,
isNewWindow: isNewWindow
)
switch plan {
case .allowInWebView:
decisionHandler(.allow)
case .launchCustomScheme(let targetURL):
if isMainFrame { activeNavigationGeneration &+= 1 }
executeExternalDispatchOnce(
action: navigationAction,
url: targetURL,
isUniversalLink: false,
requestGeneration: activeNavigationGeneration
)
decisionHandler(.cancel)
case .attemptUniversalLink(let targetURL):
if isMainFrame { activeNavigationGeneration &+= 1 }
let currentGen = activeNavigationGeneration
executeExternalDispatchOnce(
action: navigationAction,
url: targetURL,
isUniversalLink: true,
requestGeneration: currentGen
)
decisionHandler(.cancel)
case .block:
decisionHandler(.cancel)
}
}
// MARK: - WKUIDelegate (Handles target="_blank" and window.open)
func webView(
_ webView: WKWebView,
createWebViewWith configuration: WKWebViewConfiguration,
for navigationAction: WKNavigationAction,
windowFeatures: WKWindowFeatures
) -> WKWebView? {
guard navigationAction.targetFrame == nil,
let url = navigationAction.request.url else {
return nil
}
let isMainFrame = navigationAction.sourceFrame.isMainFrame
if isMainFrame {
activeNavigationGeneration &+= 1
}
let currentGen = activeNavigationGeneration
let plan = evaluateNavigationPolicy(
url: url,
navigationType: navigationAction.navigationType,
isMainFrame: isMainFrame,
isNewWindow: true
)
switch plan {
case .allowInWebView:
webView.load(navigationAction.request)
case .launchCustomScheme(let targetURL):
executeExternalDispatchOnce(
action: navigationAction,
url: targetURL,
isUniversalLink: false,
requestGeneration: currentGen
)
case .attemptUniversalLink(let targetURL):
executeExternalDispatchOnce(
action: navigationAction,
url: targetURL,
isUniversalLink: true,
requestGeneration: currentGen
)
case .block:
break
}
return nil
}
// MARK: - Pure Navigation Policy Evaluation (Zero Side Effects)
private func evaluateNavigationPolicy(
url: URL,
navigationType: WKNavigationType,
isMainFrame: Bool,
isNewWindow: Bool
) -> NavigationPlan {
guard let scheme = url.scheme?.lowercased() else {
return .block
}
let isLinkActivated = (navigationType == .linkActivated)
// 1. Evaluate non-HTTP/HTTPS Custom URL Schemes
// Note: Custom scheme allowlisting validates URI structure; it cannot guarantee target Bundle ID identity.
if scheme != "http" && scheme != "https" {
guard isMainFrame, isLinkActivated, isAllowedCustomURL(url) else {
return .block
}
return .launchCustomScheme(url)
}
// 2. Enforce HTTPS-only, default port (nil or 443), and Host Allowlists
let targetHost = url.host?.lowercased()
if isNewWindow {
guard isMainFrame, isLinkActivated, isAllowedPopupWebURL(url) else {
return .block
}
} else {
guard isAllowedWebURL(url), let host = targetHost, allowedWebHosts.contains(host) else {
return .block
}
}
// 3. Evaluate Universal Link Handoffs for designated external hosts on link activation
if let host = targetHost,
externalUniversalLinkHosts.contains(host),
isMainFrame,
isLinkActivated,
let loopKey = universalLinkLoopKey(for: url),
!isBypassedKeyActive(loopKey) {
return .attemptUniversalLink(url)
}
return .allowInWebView
}
// MARK: - Action-Level Deduplicated External Dispatch Execution
private func executeExternalDispatchOnce(
action: WKNavigationAction,
url: URL,
isUniversalLink: Bool,
requestGeneration: UInt64
) {
let actionID = ObjectIdentifier(action)
if dispatchedActionIDs.contains(actionID) {
return
}
if dispatchedActionIDs.count >= maxTrackedActionIDs {
dispatchedActionIDs.removeFirst()
}
dispatchedActionIDs.append(actionID)
if isUniversalLink {
guard let loopKey = universalLinkLoopKey(for: url) else { return }
UIApplication.shared.open(url, options: [.universalLinksOnly: true]) { [weak self] success in
// Verify view lifecycle AND generation token to prevent stale async fallback overwrites
guard let self = self,
self.isViewLoaded,
self.view.window != nil,
self.activeNavigationGeneration == requestGeneration else {
return
}
if !success {
self.recordBypassedKey(loopKey)
self.webView.load(URLRequest(url: url))
}
}
} else {
UIApplication.shared.open(url, options: [:]) { success in
if !success {
print("[WebViewDebug] Failed to launch custom scheme (app may not be installed)")
}
}
}
}
private func isAllowedWebURL(_ url: URL) -> Bool {
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
let scheme = components.scheme?.lowercased(),
scheme == "https",
components.user == nil,
components.password == nil,
(components.port == nil || components.port == 443) else {
return false
}
return true
}
private func isAllowedPopupWebURL(_ url: URL) -> Bool {
guard isAllowedWebURL(url),
let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
let host = components.host?.lowercased(),
allowedPopupHosts.contains(host),
components.fragment == nil else {
return false
}
let path = components.path
return allowedPopupPathPrefixes.contains { path == $0 || path.hasPrefix("\($0)/") }
}
private func isAllowedCustomURL(_ url: URL) -> Bool {
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
let scheme = components.scheme?.lowercased(),
let host = components.host?.lowercased(),
allowedCustomSchemes.contains(scheme),
allowedCustomHosts.contains(host),
components.user == nil,
components.password == nil,
components.port == nil, // Reject explicit ports on custom schemes
components.fragment == nil else {
return false
}
let path = components.path
if !path.isEmpty &&
path.range(of: "^/[A-Za-z0-9/_-]{1,64}$", options: .regularExpression) == nil {
return false
}
if let queryItems = components.queryItems {
var seenKeys = Set<String>()
for item in queryItems {
if seenKeys.contains(item.name) {
return false
}
seenKeys.insert(item.name)
guard allowedCustomQueryKeys.contains(item.name),
let value = item.value,
value.count <= 64,
value.range(of: "^[A-Za-z0-9_-]+$", options: .regularExpression) != nil else {
return false
}
}
}
return true
}
private func universalLinkLoopKey(for url: URL) -> String? {
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
let scheme = components.scheme?.lowercased(),
let host = components.host?.lowercased() else {
return nil
}
let portPart = (components.port != nil && components.port != 443) ? ":\(components.port!)" : ""
let significantParams = (components.queryItems ?? [])
.filter { significantLoopQueryKeys.contains($0.name) }
.sorted { $0.name < $1.name }
.map { "\($0.name)=\($0.value ?? "")" }
.joined(separator: "&")
let querySuffix = significantParams.isEmpty ? "" : "?\(significantParams)"
return "\(scheme)://\(host)\(portPart)\(components.path)\(querySuffix)"
}
private func isBypassedKeyActive(_ key: String) -> Bool {
let now = ProcessInfo.processInfo.systemUptime
bypassedUniversalLinkKeys = bypassedUniversalLinkKeys.filter {
(now - $0.value) < bypassTTLSeconds
}
return bypassedUniversalLinkKeys[key] != nil
}
private func recordBypassedKey(_ key: String) {
let now = ProcessInfo.processInfo.systemUptime
bypassedUniversalLinkKeys = bypassedUniversalLinkKeys.filter {
(now - $0.value) < bypassTTLSeconds
}
if bypassedUniversalLinkKeys.count >= maxBypassedKeys,
let oldestKey = bypassedUniversalLinkKeys.min(by: { $0.value < $1.value })?.key {
bypassedUniversalLinkKeys.removeValue(forKey: oldestKey)
}
bypassedUniversalLinkKeys[key] = now
}
}
Fixing ERR_UNKNOWN_URL_SCHEME and Package Visibility Failures in Android WebView
Deprecated Callbacks, hasGesture(), and POST Boundaries
Android deprecated shouldOverrideUrlLoading(WebView, String) in API level 24 in favor of shouldOverrideUrlLoading(WebView, WebResourceRequest). WebResourceRequest provides isForMainFrame, isRedirect, and hasGesture(). Note two official platform constraints: shouldOverrideUrlLoading is not invoked for host-initiated webView.loadUrl() calls or HTTP POST navigations, and hasGesture() can return false for legitimate async JavaScript redirects or server-side 302 hops.
Defense-in-Depth Popup Handling and Thread Isolation in WebChromeClient.onCreateWindow
Android popup behavior depends on WebSettings.setSupportMultipleWindows. If your app does not require interactive popups, keeping setSupportMultipleWindows(false) (or returning false from onCreateWindow) prevents third-party iframes from opening secondary containers—or open verified destinations via an explicit, host-controlled entry point.
When setSupportMultipleWindows(true) is enabled, WebChromeClient.onCreateWindow does not provide the destination URL in its callback signature, and no single callback covers every navigation vector. Understanding the exact thread model and callback boundaries is essential for a defense-in-depth reference approach:
shouldOverrideUrlLoading(UI Thread — Navigation & Session State Owner): Runs exclusively on the UI thread and owns all mutable popup session state (isInitialTransportLoad,isAuthorizedPopupSession,popupRedirectHops, andpopupChainStartMs). Only once a verified initial load or direct user gesture matchespolicy.isAllowedPopupUridoesshouldOverrideUrlLoadingauthorize the session for subsequent bounded HTTP 302 redirects (request.isRedirect), ensuring redirect chains tie back to an authorized session rather than trusting arbitrary redirects.shouldInterceptRequest(Background WebView IO Thread — Stateless Read-Only Guard): Runs on a non-UI WebView thread. Because it must never mutate UI-thread session state, it operates strictly as a stateless, read-only policy check onsafeClient.policy(blocking main-frame HTTP/HTTPS requests failingisAllowedPopupUriand dispatchingdisposeActivePopup()onto the main thread). Note that per Android documentation,shouldInterceptRequestis only called for the initial resource URL, not for subsequent HTTP 302 redirect URLs; subsequent redirect URLs must be evaluated byshouldOverrideUrlLoading.onPageStarted(UI Thread — Navigation-Start Fallback Check): Executes when main-frame loading starts (not as a pre-navigation filter). It updates the visible origin banner for user transparency and provides a navigation-start fallback check callingstopLoading()anddisposeActivePopup()if an unapproved destination starts loading.
Always test malicious initial URLs, cross-domain HTTP 302 chains, consecutive 302 redirects, target="_blank", window.open(), and third-party iframe triggers on target physical WebView builds.
Android 11+ Package Visibility and Deprecated canOpenURL Guidance
Under Android package visibility rules, applications running on Android 11 (API level 30) or higher and targeting API level 30 or higher (targetSdk >= 30) receive null or empty results from intent.resolveActivity() or queryIntentActivities() unless target apps are declared under <queries> in AndroidManifest.xml. Android recommends calling startActivity(intent) directly inside a try/catch for ActivityNotFoundException and SecurityException rather than expanding <queries>.
On iOS, Apple has deprecated UIApplication.canOpenURL(_:) and recommends attempting UIApplication.shared.open(_:options:completionHandler:) directly and handling any failure in the completion handler (or migrating to Universal Links to remove scheme pre-validation). LSApplicationQueriesSchemes in Info.plist is only required if legacy code continues calling canOpenURL(_:), whereas open(_:options:completionHandler:) does not require declaring schemes in Info.plist. Both <queries> and LSApplicationQueriesSchemes control query visibility—they are not security allowlists for validating untrusted web URIs.
<!-- Manifest Fragment: Merge <queries> into your existing AndroidManifest.xml -->
<!-- Required for targetSdk >= 30 on Android 11+ ONLY if calling resolveActivity or queryIntentActivities -->
<queries>
<intent>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="myapp" />
</intent>
<intent>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="partnerapp" />
</intent>
</queries>
<!-- Info.plist Fragment: Insert under the root <dict> in Info.plist -->
<!-- Legacy: Required on iOS ONLY if calling deprecated UIApplication.shared.canOpenURL; open(_:options:completionHandler:) does not require this key -->
<key>LSApplicationQueriesSchemes</key>
<array>
<string>myapp</string>
<string>partnerapp</string>
</array>
How to Safely Parse Chrome Intent URIs and Prevent Redirect Loops
Securing Intent.parseUri Against Intent Redirection Exploits
Android intent:// URIs encode a target scheme, package, and fallback URL (S.browser_fallback_url). Parsing untrusted web URIs via Intent.parseUri(rawUri, Intent.URI_INTENT_SCHEME) introduces Intent Redirection risks detailed in the Android Intent Redirection security guide and the OWASP Mobile Application Security Testing Guide. Even with Android 16 (API 36) adding platform-level default hardening, applications must enforce strict validation before dispatching Intents.

To implement fail-closed validation using AndroidX IntentSanitizer (androidx.core:core:1.9.0+, or androidx.core:core-ktx:1.9.0+ which bundles androidx.core:core) without triggering builder mutual-exclusion conflicts between allowAnyComponent() and package/component allowlist methods:
- Pre-Sanitization Checks: Immediately reject intents carrying non-null
componentorselectorfields (parsedIntent.component != null || parsedIntent.selector != null). Extract and removebrowser_fallback_urlbefore sanitization, and verify natively thatparsedIntent.data?.schememaps 1-to-1 toparsedIntent.package`` viacustomSchemeTargetPackages(ensuringmyapp://resolves strictly tocom.example.target, never another partner package). - Sanitizer Execution: Temporarily clear
parsedIntent.package= nullon the untrusted copy, executeIntentSanitizer.Builder().allowAnyComponent().allowAction(Intent.ACTION_VIEW).allowCategory(Intent.CATEGORY_BROWSABLE).allowData { ... }.build().sanitizeByThrowing(parsedIntent)(zero webpage-supplied task flags), and re-assign the validatedexpectedPackageandCATEGORY_BROWSABLEon the sanitized host-owned Intent before post-sanitization assertions. - Context-Aware Launch Flags: Inject
Intent.FLAG_ACTIVITY_NEW_TASKinside the native dispatcher (launchWithContextSafety) only whenview.context !is Activity. For domain-to-app association verification, prefer verified HTTPS Android App Links (assetlinks.json).
Preventing Infinite Fallback Loops with Monotonic Chain State
When startActivity throws ActivityNotFoundException, validate browser_fallback_url with a dedicated isAllowedFallbackUri(uri) check (strictly HTTPS, default port, verified host, explicit fallback path prefixes, no duplicate query keys, and no fragments). Reject explicit port representations on custom schemes by verifying both uri.port == -1 and !uri.encodedAuthority.orEmpty().contains(":").
Track fallback chains using SystemClock.elapsedRealtime() (avoiding wall-clock System.currentTimeMillis() jumps), isolate chains via fallbackLoopKey() (not full IETF RFC 3986 canonicalization), reset state via an explicit loadNewNavigation(webView, url) host wrapper, and route popup fallbacks out to the primary container via onPopupFallbackHandoff so unauthorized domains never load inside a popup dialog.
Reference Architecture Disclaimer: The following implementation is a defensive reference architecture. Validate API availability, delegate ordering, and lifecycle behavior against the exact AndroidX and iOS versions used by your application.
// Android - SafeWebViewModules.kt
// Reference architecture: compile and test against your specific project targets
// Requires androidx.core:core:1.9.0+ (or androidx.core:core-ktx:1.9.0+) for IntentSanitizer; targets minSdk >= 24.
package com.example.hostapp.webview
import android.app.Activity
import android.app.Dialog
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.net.Uri
import android.os.Bundle
import android.os.Message
import android.os.SystemClock
import android.util.Log
import android.view.ViewGroup
import android.widget.TextView
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.IntentSanitizer
import java.io.ByteArrayInputStream
import java.net.URISyntaxException
// 1. Policy Module (Immutable / Thread-Safe for read-only access from IO & UI threads)
class CustomUriPolicy(
val customSchemeTargetPackages: Map<String, String> = mapOf(
"myapp" to "com.example.target",
"partnerapp" to "com.partner.app"
),
val allowedCustomHosts: Set<String> = setOf("open", "product", "promo"),
val allowedCustomQueryKeys: Set<String> = setOf("id", "ref", "promo"),
val allowedWebHosts: Set<String> = setOf("example.com", "downloads.example.com"),
val allowedFallbackHosts: Set<String> = setOf("downloads.example.com", "example.com"),
val allowedFallbackPathPrefixes: List<String> = listOf("/download", "/app", "/landing"),
val allowedFallbackQueryKeys: Set<String> = setOf("id", "ref", "promo", "utm_source"),
// Isolated allowlists explicitly for popup windows; distinct from general web hosts
val allowedPopupHosts: Set<String> = setOf("example.com", "auth.example.com"),
val allowedPopupPathPrefixes: List<String> = listOf("/oauth", "/popup", "/window")
) {
val allowedCustomSchemes: Set<String> get() = customSchemeTargetPackages.keys
val allowedTargetPackages: Set<String> get() = customSchemeTargetPackages.values.toSet()
private val pathPattern = Regex("^/[A-Za-z0-9/_-]{1,64}$")
private val queryValuePattern = Regex("^[A-Za-z0-9_-]{1,64}$")
fun isAllowedWebUri(uri: Uri): Boolean {
val scheme = uri.scheme?.lowercase() ?: return false
val host = uri.host?.lowercase() ?: return false
return scheme == "https" &&
host in allowedWebHosts &&
(uri.port == -1 || uri.port == 443) &&
uri.userInfo == null
}
fun isAllowedPopupUri(uri: Uri): Boolean {
val scheme = uri.scheme?.lowercase() ?: return false
val host = uri.host?.lowercase() ?: return false
if (scheme != "https" || host !in allowedPopupHosts) return false
if ((uri.port != -1 && uri.port != 443) || uri.userInfo != null || uri.fragment != null) return false
val path = uri.path.orEmpty()
return allowedPopupPathPrefixes.any { path == it || path.startsWith("$it/") } && pathPattern.matches(path)
}
fun isAllowedFallbackUri(uri: Uri): Boolean {
val scheme = uri.scheme?.lowercase() ?: return false
val host = uri.host?.lowercase() ?: return false
if (scheme != "https" || host !in allowedFallbackHosts) return false
if ((uri.port != -1 && uri.port != 443) || uri.userInfo != null || uri.fragment != null) {
return false
}
val path = uri.path.orEmpty()
if (allowedFallbackPathPrefixes.none { path == it || path.startsWith("$it/") } ||
!pathPattern.matches(path)
) {
return false
}
// Validate query keys, enforce value syntax, and reject duplicate keys
val queryNames = uri.queryParameterNames
for (paramName in queryNames) {
if (paramName !in allowedFallbackQueryKeys) return false
val values = uri.getQueryParameters(paramName)
if (values.size != 1 || !queryValuePattern.matches(values[0])) return false
}
return true
}
fun isAllowedCustomUri(uri: Uri): Boolean {
val scheme = uri.scheme?.lowercase() ?: return false
val host = uri.host?.lowercase() ?: return false
if (scheme !in allowedCustomSchemes || host !in allowedCustomHosts) return false
// Reject network ports strictly by checking both uri.port == -1 and raw authority colon absence
val rawAuthority = uri.encodedAuthority.orEmpty()
if (uri.userInfo != null || uri.port != -1 || rawAuthority.contains(":") || uri.fragment != null) {
return false
}
val path = uri.path.orEmpty()
if (path.isNotEmpty() && !pathPattern.matches(path)) return false
// Validate query keys, enforce value syntax, and reject duplicate keys
val queryNames = uri.queryParameterNames
for (paramName in queryNames) {
if (paramName !in allowedCustomQueryKeys) return false
val values = uri.getQueryParameters(paramName)
if (values.size != 1 || !queryValuePattern.matches(values[0])) return false
}
return true
}
}
// 2. Fallback Manager: Monotonic Elapsed-Time Chain State (Isolates active chain from repeat sessions)
class FallbackLoopGuard(
private val maxHopsPerChain: Int = 3,
private val chainTtlMs: Long = 30_000L,
private val significantQueryKeys: Set<String> = setOf("id")
) {
private var chainStartElapsedMs: Long = 0L
private var fallbackHopCount: Int = 0
private val visitedInCurrentChain = mutableSetOf<String>()
fun resetChain() {
chainStartElapsedMs = 0L
fallbackHopCount = 0
visitedInCurrentChain.clear()
}
fun canLoadFallback(uri: Uri, currentWebViewUrl: String?): Boolean {
val now = SystemClock.elapsedRealtime()
if (chainStartElapsedMs == 0L || (now - chainStartElapsedMs) > chainTtlMs) {
chainStartElapsedMs = now
fallbackHopCount = 0
visitedInCurrentChain.clear()
}
val loopKey = fallbackLoopKey(uri)
val currentKey = currentWebViewUrl?.let { fallbackLoopKey(Uri.parse(it)) }
if (fallbackHopCount >= maxHopsPerChain ||
loopKey == currentKey ||
loopKey in visitedInCurrentChain
) {
return false
}
visitedInCurrentChain.add(loopKey)
fallbackHopCount++
return true
}
// Application-level loop key normalizing default HTTPS port and preserving significant query keys
private fun fallbackLoopKey(uri: Uri): String {
val scheme = uri.scheme?.lowercase().orEmpty()
val host = uri.host?.lowercase().orEmpty()
val portSuffix = if (uri.port != -1 && uri.port != 443) ":${uri.port}" else ""
val path = uri.path.orEmpty()
val sigParams = uri.queryParameterNames
.filter { it in significantQueryKeys }
.sorted()
.joinToString("&") { key -> "$key=${uri.getQueryParameter(key).orEmpty()}" }
val querySuffix = if (sigParams.isEmpty()) "" else "?$sigParams"
return "$scheme://$host$portSuffix$path$querySuffix"
}
}
// 3. Router & Fail-Closed IntentSanitizer WebViewClient (UI Thread Only)
class SafeRedirectWebViewClient(
val policy: CustomUriPolicy = CustomUriPolicy(),
val loopGuard: FallbackLoopGuard = FallbackLoopGuard(),
private val onPopupFallbackHandoff: ((fallbackUri: Uri) -> Unit)? = null
) : WebViewClient() {
// Explicit host-initiated navigation API that resets fallback chain state prior to loadUrl()
fun loadNewNavigation(webView: WebView, url: String) {
val targetUri = Uri.parse(url)
if (!policy.isAllowedWebUri(targetUri)) {
Log.w("WebViewDebug", "Blocked host-initiated navigation to untrusted URL")
return
}
loopGuard.resetChain()
webView.loadUrl(url)
}
// Dedicated fallback loader with internal validation preserving active chain state
fun loadFallbackNavigation(webView: WebView, fallbackUri: Uri) {
if (!policy.isAllowedFallbackUri(fallbackUri)) {
Log.w("WebViewDebug", "Blocked untrusted fallback navigation attempt")
return
}
webView.loadUrl(fallbackUri.toString())
}
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
return handleNavigation(
view = view,
uri = request.url,
isForMainFrame = request.isForMainFrame,
hasUserGesture = request.hasGesture(),
isPopupContext = false
)
}
fun handleNavigation(
view: WebView,
uri: Uri?,
isForMainFrame: Boolean,
hasUserGesture: Boolean,
isPopupContext: Boolean
): Boolean {
val targetUri = uri ?: return true
val scheme = targetUri.scheme?.lowercase() ?: return true
// 1. Enforce HTTPS-only & Web Host Allowlist on all HTTP/HTTPS navigations
if (scheme == "http" || scheme == "https") {
if (!policy.isAllowedWebUri(targetUri)) {
Log.w("WebViewDebug", "Blocked non-HTTPS, custom-port, or untrusted web host")
return true
}
if (hasUserGesture && isForMainFrame) {
loopGuard.resetChain()
}
return false
}
// 2. Enforce main-frame and user-gesture constraints on external app launches
if (!isForMainFrame || !hasUserGesture) {
Log.w("WebViewDebug", "Blocked non-main-frame or non-gesture scheme: $scheme")
return true
}
// 3. Parse and fail-closed sanitize Chrome intent:// URIs
if (scheme == "intent") {
return handleIntentUri(view, targetUri.toString(), isPopupContext)
}
// 4. Validate and explicitly bind allowlisted custom URL schemes to 1-to-1 verified target packages
if (policy.isAllowedCustomUri(targetUri)) {
val expectedPackage = policy.customSchemeTargetPackages[scheme] ?: return true
val viewIntent = Intent(Intent.ACTION_VIEW, targetUri).apply {
addCategory(Intent.CATEGORY_BROWSABLE)
`package` = expectedPackage
}
launchIntentSafely(view, viewIntent)
return true
}
// 5. Block all unrecognized schemes
Log.w("WebViewDebug", "Blocked unrecognized URL scheme: $scheme")
return true
}
// UI-Thread Navigation Evaluator for child popup WebViews tying 302 redirects to authorized sessions
fun handlePopupNavigation(
view: WebView,
uri: Uri?,
isForMainFrame: Boolean,
hasUserGesture: Boolean,
isRedirect: Boolean,
isInitialTransportLoad: Boolean,
isAuthorizedPopupSession: Boolean,
onAuthorizedInitialSession: () -> Unit,
canProceedPopupRedirect: () -> Boolean
): Boolean {
val targetUri = uri ?: return true
val scheme = targetUri.scheme?.lowercase() ?: return true
if (scheme == "http" || scheme == "https") {
if (!isForMainFrame) {
Log.w("WebViewDebug", "Blocked subframe HTTPS navigation inside popup")
return true
}
if (!policy.isAllowedPopupUri(targetUri)) {
Log.w("WebViewDebug", "Blocked untrusted popup HTTPS host or path navigation")
return true
}
// Authorize session only on UI thread when initial load or user tap matches allowlist
if (isInitialTransportLoad || hasUserGesture) {
onAuthorizedInitialSession()
return false
}
// Permit bounded server-side 302 redirects ONLY for previously authorized popup sessions
if (isRedirect && isAuthorizedPopupSession && canProceedPopupRedirect()) {
return false
}
Log.w("WebViewDebug", "Blocked unauthorized redirect or non-gesture popup navigation")
return true
}
return handleNavigation(view, targetUri, isForMainFrame, hasUserGesture, isPopupContext = true)
}
private fun handleIntentUri(view: WebView, rawUri: String, isPopupContext: Boolean): Boolean {
val parsedIntent = try {
Intent.parseUri(rawUri, Intent.URI_INTENT_SCHEME)
} catch (e: URISyntaxException) {
Log.w("WebViewDebug", "Malformed intent URI syntax")
return true
}
val fallbackUrl = parsedIntent.getStringExtra("browser_fallback_url")
parsedIntent.removeExtra("browser_fallback_url")
// 1-to-1 Binding: Extract target scheme and validate natively against expected target package
val dataUri = parsedIntent.data ?: return true
val targetScheme = dataUri.scheme?.lowercase() ?: return true
val expectedPackage = policy.customSchemeTargetPackages[targetScheme] ?: run {
Log.w("WebViewDebug", "Blocked intent with unmapped custom scheme: $targetScheme")
return true
}
val rawPackage = parsedIntent.`package`
if (rawPackage != expectedPackage) {
Log.w("WebViewDebug", "Blocked intent package mismatch: expected $expectedPackage")
return true
}
// Reject webpage-specified explicit components and selectors immediately
if (parsedIntent.component != null || parsedIntent.selector != null) {
Log.w("WebViewDebug", "Blocked intent with explicit component or selector")
return true
}
// Clear verified package temporarily before invoking IntentSanitizer with allowAnyComponent()
// to avoid Builder mutual-exclusion constraints while strictly rejecting untrusted flags/extras.
parsedIntent.`package` = null
val sanitizedIntent = try {
IntentSanitizer.Builder()
.allowAnyComponent()
.allowAction(Intent.ACTION_VIEW)
.allowCategory(Intent.CATEGORY_BROWSABLE)
.allowData { uri -> policy.isAllowedCustomUri(uri) }
.build()
.sanitizeByThrowing(parsedIntent)
} catch (e: SecurityException) {
Log.w("WebViewDebug", "IntentSanitizer threw SecurityException for disallowed fields or flags")
return true
} catch (e: IllegalArgumentException) {
Log.w("WebViewDebug", "IntentSanitizer rejected invalid intent arguments")
return true
}
// Re-bind verified target package + host-enforced category + post-sanitization assertions
sanitizedIntent.`package` = expectedPackage
sanitizedIntent.addCategory(Intent.CATEGORY_BROWSABLE)
val sanitizedData = sanitizedIntent.data
if (sanitizedIntent.component != null ||
sanitizedIntent.action != Intent.ACTION_VIEW ||
sanitizedIntent.`package` != expectedPackage ||
sanitizedData == null ||
!policy.isAllowedCustomUri(sanitizedData)
) {
Log.w("WebViewDebug", "Post-sanitization intent assertions failed")
return true
}
try {
launchWithContextSafety(view, sanitizedIntent)
loopGuard.resetChain()
} catch (e: ActivityNotFoundException) {
if (!fallbackUrl.isNullOrBlank()) {
val fallbackUri = Uri.parse(fallbackUrl)
if (policy.isAllowedFallbackUri(fallbackUri) &&
loopGuard.canLoadFallback(fallbackUri, view.url)
) {
if (isPopupContext) {
onPopupFallbackHandoff?.invoke(fallbackUri)
} else {
loadFallbackNavigation(view, fallbackUri)
}
} else {
Log.w("WebViewDebug", "Blocked untrusted or looping fallback URL")
}
}
} catch (e: SecurityException) {
Log.w("WebViewDebug", "SecurityException blocked intent launch")
}
return true
}
private fun launchIntentSafely(view: WebView, intent: Intent) {
try {
launchWithContextSafety(view, intent)
} catch (e: ActivityNotFoundException) {
Log.i("WebViewDebug", "No installed application handles target package/scheme")
} catch (e: SecurityException) {
Log.w("WebViewDebug", "SecurityException blocked custom scheme launch")
}
}
private fun launchWithContextSafety(view: WebView, intent: Intent) {
val safeIntent = Intent(intent)
if (view.context !is Activity) {
safeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
view.context.startActivity(safeIntent)
}
}
// 4. Lifecycle-Managed Popup WebChromeClient (Strict UI-Thread Session State & Stateless Background Guard)
class SafePopupWebChromeClient(
private val safeClient: SafeRedirectWebViewClient
) : WebChromeClient() {
private var activeDialog: Dialog? = null
private var activeChildWebView: WebView? = null
private var isDisposed: Boolean = false
private fun disposeActivePopup() {
if (isDisposed) return
isDisposed = true
val dialog = activeDialog
val child = activeChildWebView
activeDialog = null
activeChildWebView = null
dialog?.setOnDismissListener(null)
dialog?.dismiss()
child?.let {
(it.parent as? ViewGroup)?.removeView(it)
it.stopLoading()
it.webViewClient = WebViewClient()
it.webChromeClient = null
it.destroy()
}
}
override fun onCreateWindow(
view: WebView,
isDialog: Boolean,
isUserGesture: Boolean,
resultMsg: Message?
): Boolean {
if (!isUserGesture) return false
val activity = view.context as? Activity
if (activity == null || activity.isFinishing || activity.isDestroyed) {
return false
}
val transport = resultMsg?.obj as? WebView.WebViewTransport ?: return false
disposeActivePopup()
isDisposed = false
val popupDialog = Dialog(activity)
val popupRoot = android.widget.LinearLayout(activity).apply {
orientation = android.widget.LinearLayout.VERTICAL
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
}
val originBanner = TextView(activity).apply {
setPadding(24, 16, 24, 16)
setBackgroundColor(android.graphics.Color.DKGRAY)
setTextColor(android.graphics.Color.WHITE)
textSize = 12f
text = "Loading destination..."
}
popupRoot.addView(originBanner)
// All popup session state variables below are read and mutated strictly on the UI thread
var isInitialTransportLoad = true
var isAuthorizedPopupSession = false
var popupRedirectHops = 0
var popupChainStartMs = SystemClock.elapsedRealtime()
val maxPopupRedirects = 5
val maxPopupRedirectWindowMs = 30_000L
val childWebView = WebView(activity).apply {
layoutParams = android.widget.LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
settings.apply {
javaScriptEnabled = true
allowFileAccess = false
allowContentAccess = false
setSupportMultipleWindows(false)
}
webViewClient = object : WebViewClient() {
// UI Thread: Owns navigation, redirect, and session authorization state
override fun shouldOverrideUrlLoading(
childView: WebView,
request: WebResourceRequest
): Boolean {
val hasGesture = request.hasGesture()
if (hasGesture) {
popupRedirectHops = 0
popupChainStartMs = SystemClock.elapsedRealtime()
}
val result = safeClient.handlePopupNavigation(
view = childView,
uri = request.url,
isForMainFrame = request.isForMainFrame,
hasUserGesture = hasGesture,
isRedirect = request.isRedirect,
isInitialTransportLoad = isInitialTransportLoad,
isAuthorizedPopupSession = isAuthorizedPopupSession,
onAuthorizedInitialSession = {
isAuthorizedPopupSession = true
},
canProceedPopupRedirect = {
val withinWindow = (SystemClock.elapsedRealtime() - popupChainStartMs) <= maxPopupRedirectWindowMs
if (withinWindow && popupRedirectHops < maxPopupRedirects) {
popupRedirectHops++
true
} else {
false
}
}
)
isInitialTransportLoad = false
return result
}
// Background WebView IO Thread: Strictly stateless, read-only policy check.
// Never mutates UI-thread session state; covers initial resource URL only (not subsequent 302 hops).
override fun shouldInterceptRequest(
childView: WebView,
request: WebResourceRequest
): WebResourceResponse? {
if (request.isForMainFrame) {
val targetUri = request.url
val scheme = targetUri?.scheme?.lowercase()
if ((scheme == "http" || scheme == "https") && !safeClient.policy.isAllowedPopupUri(targetUri)) {
Log.w("WebViewDebug", "Blocked unapproved popup main-frame request in shouldInterceptRequest")
childView.post { disposeActivePopup() }
return WebResourceResponse("text/plain", "utf-8", ByteArrayInputStream(ByteArray(0)))
}
}
return super.shouldInterceptRequest(childView, request)
}
// UI Thread: Navigation-start fallback check & origin display (not a pre-navigation filter)
override fun onPageStarted(childView: WebView, url: String?, favicon: android.graphics.Bitmap?) {
super.onPageStarted(childView, url, favicon)
isInitialTransportLoad = false
val uri = url?.let { Uri.parse(it) }
if (uri == null || !safeClient.policy.isAllowedPopupUri(uri)) {
Log.w("WebViewDebug", "Navigation-start fallback check terminated unapproved popup URL")
childView.stopLoading()
disposeActivePopup()
return
}
isAuthorizedPopupSession = true
val scheme = uri.scheme?.lowercase() ?: "https"
val host = uri.host?.lowercase() ?: "Unknown"
originBanner.text = "Origin: $scheme://$host"
}
}
webChromeClient = object : WebChromeClient() {
override fun onCloseWindow(window: WebView?) {
disposeActivePopup()
}
}
}
popupRoot.addView(childWebView)
popupDialog.setContentView(popupRoot)
popupDialog.setOnDismissListener {
disposeActivePopup()
}
activeDialog = popupDialog
activeChildWebView = childWebView
popupDialog.show()
transport.webView = childWebView
resultMsg.sendToTarget()
return true
}
fun destroyPopups() {
disposeActivePopup()
}
}
// 5. Complete Host Activity Registration & Lifecycle Cleanup Example (JavaScript Enabled on Main WebView)
class SafeWebViewActivity : AppCompatActivity() {
private lateinit var webView: WebView
private lateinit var safeClient: SafeRedirectWebViewClient
private lateinit var popupChromeClient: SafePopupWebChromeClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0) {
WebView.setWebContentsDebuggingEnabled(true)
}
val policy = CustomUriPolicy()
val loopGuard = FallbackLoopGuard()
safeClient = SafeRedirectWebViewClient(
policy = policy,
loopGuard = loopGuard,
onPopupFallbackHandoff = { fallbackUri ->
popupChromeClient.destroyPopups()
safeClient.loadFallbackNavigation(webView, fallbackUri)
}
)
popupChromeClient = SafePopupWebChromeClient(safeClient)
webView = WebView(this).apply {
settings.apply {
// Enable JavaScript explicitly for trusted landing pages requiring JS redirects or window.open()
javaScriptEnabled = true
allowFileAccess = false
allowContentAccess = false
// Enable multiple windows only if hosting interactive popup containers
setSupportMultipleWindows(true)
}
webViewClient = safeClient
webChromeClient = popupChromeClient
}
setContentView(webView)
// Use explicit host wrapper rather than bare webView.loadUrl()
safeClient.loadNewNavigation(webView, "https://example.com/landing")
}
override fun onDestroy() {
popupChromeClient.destroyPopups()
(webView.parent as? ViewGroup)?.removeView(webView)
webView.destroy()
super.onDestroy()
}
}
Frequently Asked Questions (FAQ)
Why does Android WebView show net::ERR_UNKNOWN_URL_SCHEME even when the target app is installed?
Why does shouldOverrideUrlLoading fail to fire when my app calls WebView loadUrl directly?
Why do target blank links with custom schemes fail silently inside WKWebView?
Summary and Decision Framework
Resolving WebView deep-linking redirection failures requires isolating WebView engine behavior from host application navigation policies. By reproducing navigation events in Chrome DevTools or Safari Web Inspector, confining Android popup session state strictly to the UI thread while pairing stateless initial-request screening with session-authorized 302 redirect checks, enforcing fail-closed IntentSanitizer allowlists, and protecting iOS Universal Link fallbacks against stale async overwrites and duplicate delegate launches, engineering teams can reduce broken user journeys and help prevent client-side redirection vulnerabilities.
After container-level native delegates and fallback paths are verified, engineering teams should also validate end-to-end attribution landing pages and One-Click Launch routing chains using platforms such as OpoInstall to confirm parameter preservation across browser-to-app transitions.
Entity Glossary
| Term | Definition | Related Entity | Search Intent Role |
|---|---|---|---|
| WebView | An embedded native UI component used to render web pages inside a mobile application. | WebViewClient / WKWebView |
Informational / Technical |
| Custom URL Scheme | An app-registered URI prefix (e.g., myapp://) enabling external navigation into native screens. |
Intent.ACTION_VIEW |
Technical / Informational |
| WKNavigationDelegate | The WebKit protocol allowing a host app to accept, cancel, or redirect navigation actions in WKWebView. |
decidePolicyForNavigationAction |
Technical |
| WKUIDelegate | The WebKit protocol responsible for handling new-window creation requests in WKWebView. |
createWebViewWith |
Technical |
| WebResourceRequest | The Android API 24+ object encapsulating URL, frame, HTTP method, redirect, and gesture metadata. | shouldOverrideUrlLoading |
Technical |
| WebChromeClient | The Android WebView callback interface handling JavaScript dialogs, progress, and onCreateWindow. |
WebViewTransport |
Technical |
| IntentSanitizer | The AndroidX Core utility used to filter or strictly validate untrusted Intent fields before dispatch. | Intent Redirection Defense | Technical / Security |
| Universal Links | Apple’s HTTPS-based deep-linking standard tying verified web domains to installed iOS applications. | Associated Domains | Technical / Informational |
| Package Visibility | Android 11+ (targetSdk >= 30) OS filtering restricting which installed apps a host app can query via PackageManager. |
<queries> Manifest Tag |
Technical |
| Intent URI | A structured Android URI (intent://) encoding target package, scheme, and browser fallback URLs. |
Intent.URI_INTENT_SCHEME |
Technical |
Compatibility Baseline and Verification Status
-
Intended Compatibility Targets: Android
minSdk 24,compileSdk 34/35,targetSdk 34/35(Android 14/15), Android 16 (API 36) Intent Redirection hardening context,androidx.core:core:1.9.0+(IntentSanitizer); iOS 15.0–18.0 (isInspectablegated on iOS 16.4+), Xcode 15/16, Swift 5.9/6.0. -
Verification Status:
-
Static API & Specification Review: Completed against official Android Developers, AndroidX Core, Apple Developer, IETF RFC 3986, and OWASP MASTG specifications.
-
Compile & Physical Device Verification: Not yet executed in this review cycle. Teams must compile and execute physical device regression covering malicious initial popup URLs, cross-domain 302 chains, consecutive 302 hops, third-party iframe window creation, Android App Links (
assetlinks.json), iOS Associated Domains (AASA caching), stale async Universal Link cancellation,intent://fallback chains, andActivityNotFoundExceptiondispatching prior to production rollout.
-
References
Share this article



