如何排查 Android 和 iOS 上的 WebView 重定向错误?

opoinstall
2026-11-19
5 min read

webview-safe-fallback-loop-prevention.webp

如何排查 Android 和 iOS 上的 WebView 重定向错误?首先确认故障是涉及标准的 HTTPS 导航、自定义 URL Scheme、Android intent:// URI 还是新窗口请求,然后通过 Chrome DevTools 或 Safari Web Inspector 检查导航过程,并追踪相应的原生代理(shouldOverrideUrlLoading、onCreateWindow、decidePolicyForNavigationAction 或 createWebViewWith)。验证目标 App 解析、URI 白名单、frame 与用户交互策略以及回退路由,从而将容器级错误与操作系统调度失败隔离开来。

当嵌入式的 Android Chromium WebView 或 iOS WebKit WKWebView 无法将导航请求路由到预期目的地时,就会发生 WebView 重定向错误。典型原因包括不支持的自定义 URL Scheme、未处理的 target="_blank" 请求、缺少软件包可见性声明以及被拒绝或陷入死循环的回退重定向。

为什么嵌入式 Android WebView 和 iOS WKWebView 容器会丢弃重定向

分层的 WebView 重定向架构揭示了原生策略与操作系统调度失败的原因。

在调试重定向故障时,工程团队必须将WebView 引擎行为(Chromium 或 WebKit 如何解析 URL、frame 目标和弹窗事件)与宿主应用策略(应用提供的 WebViewClient、WebChromeClient、WKNavigationDelegate 或 WKUIDelegate 如何评估用户交互类型、白名单和外部 App 移交)区分开来。独立浏览器内置了 URI 调度程序和链接移交处理器,而 android.webkit.WebView 和苹果的 WKWebView 是嵌入式渲染组件,默认期望标准的 http:// 或 https:// 网络响应。

当网页触发自定义 Scheme(例如 myapp://product/42)或 Android intent:// 链接且没有活动的代理重写时,默认的容器行为在各个平台上会有所不同:

  • Android Chromium WebView:根据 Android WebViewClient 规范,如果没有分配自定义 WebViewClient,WebView 可能会请求 Activity Manager 通过可用的系统处理器解析 URL。当分配了自定义 WebViewClient 且 shouldOverrideUrlLoading 针对不支持的自定义 Scheme 返回 false 时,WebView 会继续在 Chromium 内部加载它并呈现 net::ERR_UNKNOWN_URL_SCHEME。
  • iOS WebKit WKWebView:WebKit 内部会拒绝非 HTTP Scheme 并中止导航,除非宿主的 WKNavigationDelegate 拦截该请求并将其转发给 UIApplication,这通常会导致静默失败或触发 NSURLErrorUnsupportedURL。

还要注意,苹果的使用智能 App 横幅推广 App (Promoting Apps with Smart App Banners) 是一个 Safari 支持功能,专为独立的 Safari 浏览设计,而不是嵌入式 WKWebView 导航 API,应将其与应用内自定义 URL Scheme 重定向分开评估。

一目了然

  • 将引擎行为与宿主策略隔离:排查导航失败是发生在网页引擎内部(Chromium/WebKit)、原生代理重写内部,还是在操作系统包解析边界。
  • 在编码前检查实时重定向:使用 Chrome DevTools (chrome://inspect) 和 Safari Web Inspector (isInspectable = true) 捕获 3xx 重定向链、targetFrame 状态和手势标志。
  • 实施平台适配的 URI 和 Intent 验证:在 Android 上,通过 IntentSanitizer 在没有网页提供的任务标志的情况下,将自定义 Scheme 和 intent:// 目标 1 对 1 绑定到已验证的软件包;在 iOS 上,验证完整的自定义 URI 结构(在需要验证应用与域同一性的地方依靠通用链接),并拒绝两个平台上的重复查询键。
  • 对弹窗和竞态条件应用纵深防御:将 Android 弹窗会话状态严格限制在 UI 线程中,同时理解 shouldInterceptRequest 和 shouldOverrideUrlLoading 跨界的回调边界,并通过操作级去重和导航生成令牌,将纯策略检查与 iOS WKWebView 中的外部调度副作用隔离开来。

WebView 重定向错误的常见原因与验证步骤

将观察到的客户端错误映射到底层容器故障机制

使用下方的诊断矩阵将观察到的 WebView 症状映射到常见的平台根本原因、验证步骤和针对性修复:

观察到的症状或错误 目标平台 常见根本原因 诊断验证步骤 针对性修复
WebView 显示 net::ERR_UNKNOWN_URL_SCHEME Android WebView 自定义 WebViewClient 返回 false 或缺少 Scheme 白名单 检查 shouldOverrideUrlLoading 中的 request.url 拦截白名单内的 URI 并分发 1 对 1 绑定包名的 Intent.ACTION_VIEW
点击自定义 Scheme 链接时静默挂起 iOS WKWebView 当 WKNavigationDelegate 返回 .allow 时,WebKit 会中止非 HTTP URI 在 decidePolicyForNavigationAction 中记录 navigationAction.request.url 通过 UIApplication.shared.open 路由经过验证的 Scheme 并传递 .cancel
target="_blank" 在 WebView 中替换当前页面 Android WebView setSupportMultipleWindows(false) 将新窗口视为顶级加载 检查 webView.settings.supportMultipleWindows() 仅在需要独立弹窗容器时启用 setSupportMultipleWindows(true)
target="_blank" 不起作用或丢弃 OAuth 302 重定向 Android WebView 缺少 onCreateWindow,或者子客户端阻止了缺少 hasGesture() 的 isRedirect 跳数 检查 onCreateWindow、request.isRedirect 和 shouldInterceptRequest 日志 附加一个带有 UI 线程会话状态和有界 isRedirect 跳数的视图托管弹窗 WebView
带有 target="_blank" 或 window.open() 的链接无响应 iOS WKWebView 新窗口导航设置 targetFrame == nil 并需要 WKUIDelegate 检查 navigationAction.targetFrame == nil 在 decidePolicyForNavigationAction 中检测 targetFrame == nil 并通过 WKUIDelegate 处理
目标 App 已安装,但打开了回退页面 Android 11+ (targetSdk >= 30) 缺少 <queries> 声明导致 resolveActivity() 或 queryIntentActivities() 为不可见软件包返回不完整的结果 在 resolveActivity() 周围添加应用级日志记录,并通过 adb logcat 检查输出 如果预先检查则声明 <queries> intent,或者直接使用捕获 ActivityNotFoundException 的 startActivity
JavaScript 定时器重定向未能打开外部 App iOS / Android 自动化脚本重定向缺少用户交互信号 检查 request.hasGesture() (Android) 或 navigationType (iOS) 将重定向绑定到直接用户点击,并定义明确的宿主手势策略
通用链接 (Universal Link) 在 WKWebView 内部加载而不是在目标 App 中加载 iOS WKWebView 浏览上下文、域名关系或 JS 导航使加载保持在 WebKit 中 检查 decidePolicyForNavigationAction 中的 navigationType 和 host 对允许的外部 host 调用带有 .universalLinksOnly: true 的 UIApplication.shared.open

五分钟 WebView 重定向快速排查清单

  • 第 1 步:在 DevTools 中检查协议 Scheme:验证页面发出的是 https://、自定义 Scheme 还是 intent:// URI,并确认它未被内容安全策略 (CSP) 阻止。
  • 第 2 步:检查 Frame 层级:检查触发源是否源自第三方 <iframe> 内部(!isMainFrame)。宿主应用可能会有意阻止从第三方 iframe 发起的外部 App 唤起。
  • 第 3 步:区分重定向与定时器:检查非手势导航是授权的 HTTP 3xx 服务器重定向(Android 上的 request.isRedirect)还是未经提示的 JavaScript 定时器。
  • 第 4 步:检查新窗口触发器:确认 target="_blank" 或 window.open() 是否创建了新窗口请求(iOS 上的 targetFrame == nil 或 Android 上的 onCreateWindow)。
  • 第 5 步:验证 OS 软件包解析:对于 Android 11+ 上目标 API 为 30+ 的应用,确认预检 resolveActivity() 调用是否由于缺少 <queries> 声明而失败。

以下诊断工作流说明了隔离容器重定向故障的顺序排查路径:

[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)

如何使用远程调试工具检查 WebView 导航事件

在 Android 上通过 Chrome DevTools 和 ADB Logcat 启用远程调试

在修改原生代理之前,验证加载的网页是否发出了预期的重定向。根据Android Chrome DevTools 远程调试指南,通过检查 ApplicationInfo.FLAG_DEBUGGABLE 并调用 WebView.setWebContentsDebuggingEnabled(true),在开发构建中显式启用远程 WebView 调试。切勿在生产版本中启用调试:

// Android - 仅在可调试版本中启用 WebView 调试
if (applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0) {
    WebView.setWebContentsDebuggingEnabled(true)
}

通过 USB 连接设备,在桌面端 Chrome 中打开 chrome://inspect/#devices,并保持勾选 Preserve log 的情况下监控 Network 选项卡。同时通过 adb logcat 过滤原生运行时日志,以捕获 ActivityNotFoundException、SecurityException 或自定义包装器日志。请注意,遗留 shouldOverrideUrlLoading(WebView, String) 签名的弃用警告出现在 Android Studio / Gradle 编译期间,而不是运行时 adb logcat 中:

# 终端 - 过滤 logcat 中的自定义 WebView 标签和 ActivityTaskManager intent 解析
adb logcat -s "WebViewDebug" "ActivityTaskManager" "PackageManager"

在 iOS 上配置 isInspectable 并附加 Safari Web Inspector 与 Xcode 控制台

从 iOS 16.4 和 macOS 13.3 开始,苹果要求应用通过 WKWebView.isInspectable 进行选择加入(默认为 false)。在 #if DEBUG 块内部启用 webView.isInspectable = true:

// iOS - 在 iOS 16.4+ 调试版本中启用 Safari Web Inspector 选择加入
#if DEBUG
if #available(iOS 16.4, *) {
    webView.isInspectable = true
}
#endif

在物理 iOS 设备上,导航至设置 > App > Safari > 高级(在较旧的 iOS 版本中为设置 > Safari > 高级)并启用网页检查器 (Web Inspector)。通过 USB 连接,打开桌面端 Safari 的开发 (Develop) 菜单,并同时监控 Xcode 控制台以获取原生的 decidePolicyForNavigationAction、createWebViewWith 和 UIApplication.shared.open 完成输出。

Android WebView 和 iOS WKWebView 使用不同的原生导航和弹窗处理器。

解决 iOS WKWebView 中静默丢弃新窗口和缺少用户手势的问题

在 WKNavigationDelegate 和 WKUIDelegate 之间将策略评估与副作用分离

当网页链接指定 target="_blank" 或 window.open() 时,WebKit 会创建一个新窗口导航请求,其中 navigationAction.targetFrame 为 nil,这涉及 WKNavigationDelegate 和 WKUIDelegate 双方。如果宿主应用未实现 webView(_:createWebViewWithConfiguration:for:windowFeatures:),WebKit 将无法生成辅助 WebView,导航可能会表现为静默失败。

为了防止当两个代理都检查请求时重复启动外部 App 或双重递增生成令牌,请将纯策略评估(evaluateNavigationPolicy)与执行副作用分离,并通过特定的 WKNavigationAction 实例(ObjectIdentifier(navigationAction))进行去重,而不是纯粹依赖可能抑制用户有意快速重复点击的粗略时间阈值。直接在 decidePolicyForNavigationAction 中评估 navigationAction.targetFrame == nil:如果评估返回外部移交计划,则执行一次(记录 WKNavigationAction 标识符)并传递 .cancel;如果它为白名单弹窗 URL 返回 .allowInWebView,则传递 .allow,以便 createWebViewWith 安全加载弹窗。务必在目标 iOS 版本上验证准确的代理回调顺序。

通用链接上下文、异步竞态安全与自定义 Scheme 身份

通用链接移交取决于源浏览上下文、域名关系和关联域名配置(通过目标服务器的 apple-app-site-association 文件验证)。苹果的技术说明 TN3155: 调试通用链接 (Debugging universal links) 记录了 Safari 中的同域名导航如何倾向于停留在浏览器中,而不同的子域名会改变适用性。务必在 WKWebView 内部的目标 iOS 版本上测试关联域名行为。

当调用 UIApplication.shared.open(url, options: [.universalLinksOnly: true]) 时,防范异步导航竞态条件:如果用户在系统处理通用链接移交期间发起任何后续的主框架导航尝试,返回 false 的未保护完成处理程序可能会覆盖用户较新的导航状态。在每一次新的主框架导航评估(包括被阻止或重定向的尝试)时递增单调的 activeNavigationGeneration 令牌,以便立即使任何挂起的先前异步回退失效,并在重新加载回退 URL 之前验证 self.activeNavigationGeneration == requestGeneration 以及 self.isViewLoaded && self.view.window != nil。

遵守两个严格的安全边界:

  • WKNavigationType 分类:根据苹果的 WKNavigationType 文档,formSubmitted 表示提交表单的请求,而不是链接点击,并且页面脚本可以以编程方式提交表单。将外部 App 移交限制为 WebKit 分类的 .linkActivated 事件与 sourceFrame.isMainFrame 及完整 URI 白名单的结合,而不是将 .linkActivated 视为独立的密码手势令牌。
  • 自定义 Scheme 唯一性与参数污染:根据苹果关于为您的 App 定义自定义 URL Scheme (Defining a Custom URL Scheme for Your App) 的指南,多个 App 可以声明相同的自定义 Scheme。isAllowedCustomURL(_:) 验证的是 URI 结构(Scheme、Host、默认端口 nil、路径模式、无 userinfo/fragment 且拒绝重复查询键),而不是目标 Bundle ID 身份。当需要应用身份绑定时,请使用经过域名验证的通用链接。

参考架构免责声明:以下实现为防御性参考架构。请针对您的应用程序所使用的具体 AndroidX 和 iOS 版本验证 API 可用性、代理顺序和生命周期行为。

// iOS - WebViewContainerController.swift
// 参考架构:针对您的具体项目目标(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!

    // 外部自定义 URL Scheme、host 和查询键的显式白名单
    private let allowedCustomSchemes: Set<String> = ["myapp", "partnerapp"]
    private let allowedCustomHosts: Set<String> = ["open", "product", "promo"]
    private let allowedCustomQueryKeys: Set<String> = ["id", "ref", "promo"]

    // 主 WebView 容器内允许的 HTTPS host 显式白名单
    private let allowedWebHosts: Set<String> = [
        "example.com",
        "m.example.com",
        "links.example.com"
    ]

    // 专门用于子弹窗窗口的隔离白名单 (target="_blank")
    private let allowedPopupHosts: Set<String> = ["example.com", "auth.example.com"]
    private let allowedPopupPathPrefixes: [String] = ["/oauth", "/popup", "/window"]

    // 在链接激活时尝试原生 App 移交的外部通用链接 host
    private let externalUniversalLinkHosts: Set<String> = ["links.example.com"]
    
    // 在每次新的主框架导航尝试时递增的单调导航生成令牌
    private var activeNavigationGeneration: UInt64 = 0

    // 防止对同一个 WKNavigationAction 进行重复分发的操作级去重
    private var dispatchedActionIDs: [ObjectIdentifier] = []
    private let maxTrackedActionIDs = 16

    // 以规范化的通用链接键为键的单调运行时间 TTL 有界绕过缓存
    private var bypassedUniversalLinkKeys: [String: TimeInterval] = [:]
    private let maxBypassedKeys = 10
    private let bypassTTLSeconds: TimeInterval = 300
    // 调整重要的查询键以匹配您应用程序的实际路由参数
    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)

        // 在每次主框架导航尝试时递增生成令牌(包括被阻止的尝试)
        // 从而使任何挂起的先前异步通用链接回退立即失效。
        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 (处理 target="_blank" 和 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: - 纯导航策略评估(零副作用)

    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. 评估非 HTTP/HTTPS 自定义 URL Scheme
        // 注意:自定义 Scheme 白名单验证 URI 结构;它无法保证目标 Bundle ID 身份。
        if scheme != "http" && scheme != "https" {
            guard isMainFrame, isLinkActivated, isAllowedCustomURL(url) else {
                return .block
            }
            return .launchCustomScheme(url)
        }

        // 2. 强制仅 HTTPS、默认端口(nil 或 443)以及 Host 白名单
        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. 在链接激活时评估指定外部 host 的通用链接移交
        if let host = targetHost,
           externalUniversalLinkHosts.contains(host),
           isMainFrame,
           isLinkActivated,
           let loopKey = universalLinkLoopKey(for: url),
           !isBypassedKeyActive(loopKey) {
            return .attemptUniversalLink(url)
        }

        return .allowInWebView
    }

    // MARK: - 操作级去重的外部调度执行

    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
                // 验证视图生命周期 AND 生成令牌以防止陈旧的异步回退覆盖
                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] 无法启动自定义 Scheme(可能未安装 App)")
                }
            }
        }
    }

    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, // 拒绝自定义 Scheme 上的显式端口
              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
    }
}

修复 Android WebView 中的 ERR_UNKNOWN_URL_SCHEME 和软件包可见性故障

已弃用的回调、hasGesture() 和 POST 边界

Android 在 API 级别 24 中废弃了 shouldOverrideUrlLoading(WebView, String),转而支持 shouldOverrideUrlLoading(WebView, WebResourceRequest)。WebResourceRequest 提供了 isForMainFrame、isRedirect 以及 hasGesture()。请注意两个官方平台约束:对于宿主发起的 webView.loadUrl() 调用或 HTTP POST 导航,不会调用 shouldOverrideUrlLoading;并且对于合法的异步 JavaScript 重定向或服务器端 302 跳数,hasGesture() 可能会返回 false。

WebChromeClient.onCreateWindow 中的纵深防御弹窗处理与线程隔离

Android 弹窗行为取决于 WebSettings.setSupportMultipleWindows。如果您的应用不需要交互式弹窗,保持 setSupportMultipleWindows(false)(或从 onCreateWindow 返回 false)可以防止第三方 iframe 打开辅助容器——或者通过显式的、宿主控制的入口点打开经过验证的目的地。

当启用 setSupportMultipleWindows(true) 时,WebChromeClient.onCreateWindow 的回调签名中并未提供目标 URL,且没有单一回调能够覆盖所有导航向量。理解确切的线程模型和回调边界对于纵深防御参考方法至关重要:

  • shouldOverrideUrlLoading(UI 线程 — 导航与会话状态所有者):专在 UI 线程上运行,并拥有所有可变的弹窗会话状态(isInitialTransportLoad、isAuthorizedPopupSession、popupRedirectHops 和 popupChainStartMs)。只有当经过验证的初始加载或直接用户手势与 policy.isAllowedPopupUri 匹配时,shouldOverrideUrlLoading 才会授权该会话进行后续有界的 HTTP 302 重定向(request.isRedirect),从而确保重定向链回溯到授权会话,而不是信任任意重定向。
  • shouldInterceptRequest(后台 WebView IO 线程 — 无状态只读保护):运行在非 UI 的 WebView 线程上。由于它绝不能修改 UI 线程的会话状态,它严格作为对 safeClient.policy 的无状态、只读策略检查(阻止未通过 isAllowedPopupUri 的主框架 HTTP/HTTPS 请求,并在主线程上调度 disposeActivePopup())。请注意,根据 Android 文档,shouldInterceptRequest 仅针对初始资源 URL 调用,不针对后续的 HTTP 302 重定向 URL;后续的重定向 URL 必须由 shouldOverrideUrlLoading 进行评估。
  • onPageStarted(UI 线程 — 导航开始回退检查):在主框架加载开始时执行(而不是作为预导航过滤器)。它更新用于用户透明度的可见来源横幅,并提供一个导航开始回退检查,如果未经批准的目的地开始加载,则调用 stopLoading() 和 disposeActivePopup()。

务必在目标物理 WebView 构建上测试恶意的初始 URL、跨域 HTTP 302 链、连续 302 跳数、target="_blank"、window.open() 以及第三方 iframe 触发器。

Android 11+ 软件包可见性和已弃用的 canOpenURL 指南

根据 Android 软件包可见性规则,运行在 Android 11(API 级别 30)或更高版本且目标 API 级别为 30 或更高(targetSdk >= 30)的应用从 intent.resolveActivity() 或 queryIntentActivities() 接收到的是 null 或空结果,除非目标 App 在 AndroidManifest.xml 中的 <queries> 下声明。Android 建议直接在捕获 ActivityNotFoundException 和 SecurityException 的 try/catch 块内调用 startActivity(intent),而不是扩展 <queries>。

在 iOS 上,苹果已弃用 UIApplication.canOpenURL(_:),并建议直接尝试 UIApplication.shared.open(_:options:completionHandler:) 并在完成处理程序中处理任何失败(或迁移到通用链接以消除 Scheme 预验证)。Info.plist 中的 LSApplicationQueriesSchemes 仅在遗留代码继续调用 canOpenURL(_:) 时才需要,而 open(_:options:completionHandler:) 不需要在此处声明 Scheme。<queries> 和 LSApplicationQueriesSchemes 都控制查询可见性——它们不是用于验证不受信任的网页 URI 的安全白名单。

<!-- 清单片段:将 <queries> 合并到您现有的 AndroidManifest.xml 中 -->
<!-- 仅当在 Android 11+ 上调用 resolveActivity 或 queryIntentActivities 且 targetSdk >= 30 时才需要 -->
<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 片段:插入到 Info.plist 的根 <dict> 下方 -->
<!-- 遗留:仅在 iOS 上调用已弃用的 UIApplication.shared.canOpenURL 时需要;open(_:options:completionHandler:) 不需要此键 -->
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>myapp</string>
    <string>partnerapp</string>
</array>

如何安全解析 Chrome Intent URI 并防止重定向循环

保护 Intent.parseUri 以防范 Intent 重定向漏洞

Android intent:// URI 编码了目标 Scheme、软件包和回退 URL(S.browser_fallback_url)。通过 Intent.parseUri(rawUri, Intent.URI_INTENT_SCHEME) 解析不受信任的网页 URI 会引入Android Intent 重定向安全指南和 OWASP 移动应用安全测试指南中详述的Intent 重定向风险。即使 Android 16 (API 36) 增加了平台级默认加固,应用在分发 Intent 之前也必须强制执行严格的验证。

分层的 URI 验证在外部应用分发之前阻止不安全的 WebView intent。

若要使用 AndroidX IntentSanitizer(androidx.core:core:1.9.0+ 或捆绑了 androidx.core:core 的 androidx.core:core-ktx:1.9.0+)实现故障关闭验证,且不引发 allowAnyComponent() 与软件包/组件白名单方法之间的构建器互斥冲突:

  • 预净化检查:立即拒绝带有非空 component 或 selector 字段的 intent(parsedIntent.component != null || parsedIntent.selector != null)。在净化前提取并移除 browser_fallback_url,并通过 customSchemeTargetPackages 原生验证 parsedIntent.data?.scheme 是否与 parsedIntent.package 1 对 1 映射(确保 myapp:// 严格解析为 com.example.target,绝不解析为其他合作伙伴软件包)。
  • 净化器执行:在不受信任的副本上临时清除 parsedIntent.package = null,执行 IntentSanitizer.Builder().allowAnyComponent().allowAction(Intent.ACTION_VIEW).allowCategory(Intent.CATEGORY_BROWSABLE).allowData { ... }.build().sanitizeByThrowing(parsedIntent)(零网页提供的任务标志),并在后净化断言之前,在受宿主拥有的已净化 Intent 上重新分配经过验证的 expectedPackage 和 CATEGORY_BROWSABLE。
  • 上下文感知启动标志:仅当 view.context !is Activity 时,才在原生调度器(launchWithContextSafety)中注入 Intent.FLAG_ACTIVITY_NEW_TASK。对于域到应用关联验证,请首选经过验证的 HTTPS Android App Links (assetlinks.json)。

使用单调链状态防止无限回退循环

当 startActivity 抛出 ActivityNotFoundException 时,通过专用的 isAllowedFallbackUri(uri) 检查验证 browser_fallback_url(严格要求 HTTPS、默认端口、经过验证的主机、显式回退路径前缀、无重复查询键且无 fragment)。通过同时验证 uri.port == -1 且 !uri.encodedAuthority.orEmpty().contains(":"),拒绝自定义 Scheme 上的显式端口表示。

使用 SystemClock.elapsedRealtime()(避免挂钟 System.currentTimeMillis() 跳跃)追踪回退链,通过 fallbackLoopKey()(而不是完整的 IETF RFC 3986 规范化)隔离链,通过显式的 loadNewNavigation(webView, url) 宿主包装器重置状态,并将弹窗回退通过 onPopupFallbackHandoff 路由到主容器,从而使未授权的域绝不会加载到弹窗对话框中。

参考架构免责声明:以下实现为防御性参考架构。请针对您的应用程序所使用的具体 AndroidX 和 iOS 版本验证 API 可用性、代理顺序和生命周期行为。

// Android - SafeWebViewModules.kt
// 参考架构:针对您的具体项目目标进行编译和测试
// 需要 androidx.core:core:1.9.0+(或 androidx.core:core-ktx:1.9.0+)来使用 IntentSanitizer;目标 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. 策略模块(不可变/线程安全,供来自 IO 和 UI 线程的只读访问使用)
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"),
    // 专门针对弹窗窗口显式设立的隔离白名单;与通用 web host 不同
    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
        }

        // 验证查询键、强制值语法并拒绝重复键
        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

        // 通过同时检查 uri.port == -1 且原始 authority 中没有冒号来严格拒绝网络端口
        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

        // 验证查询键、强制值语法并拒绝重复键
        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. 回退管理器:单调已过时间链状态(将活动链与重复会话隔离)
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
    }

    // 规范化默认 HTTPS 端口并保留重要查询键的应用级循环键
    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. 路由器和故障关闭的 IntentSanitizer WebViewClient(仅限 UI 线程)
class SafeRedirectWebViewClient(
    val policy: CustomUriPolicy = CustomUriPolicy(),
    val loopGuard: FallbackLoopGuard = FallbackLoopGuard(),
    private val onPopupFallbackHandoff: ((fallbackUri: Uri) -> Unit)? = null
) : WebViewClient() {

    // 显式的宿主发起的导航 API,在 loadUrl() 之前重置回退链状态
    fun loadNewNavigation(webView: WebView, url: String) {
        val targetUri = Uri.parse(url)
        if (!policy.isAllowedWebUri(targetUri)) {
            Log.w("WebViewDebug", "阻止了对不受信任 URL 的宿主发起导航")
            return
        }
        loopGuard.resetChain()
        webView.loadUrl(url)
    }

    // 带有内部验证的专用回退加载器,可保留活动链状态
    fun loadFallbackNavigation(webView: WebView, fallbackUri: Uri) {
        if (!policy.isAllowedFallbackUri(fallbackUri)) {
            Log.w("WebViewDebug", "阻止了不受信任的回退导航尝试")
            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. 在所有 HTTP/HTTPS 导航上强制执行仅 HTTPS 和 Web Host 白名单
        if (scheme == "http" || scheme == "https") {
            if (!policy.isAllowedWebUri(targetUri)) {
                Log.w("WebViewDebug", "阻止了非 HTTPS、自定义端口或不受信任的 web host")
                return true
            }
            if (hasUserGesture && isForMainFrame) {
                loopGuard.resetChain()
            }
            return false
        }

        // 2. 在外部 App 唤起上强制执行主框架和用户手势约束
        if (!isForMainFrame || !hasUserGesture) {
            Log.w("WebViewDebug", "阻止了非主框架或非手势 Scheme: $scheme")
            return true
        }

        // 3. 解析并以故障关闭方式净化 Chrome intent:// URI
        if (scheme == "intent") {
            return handleIntentUri(view, targetUri.toString(), isPopupContext)
        }

        // 4. 验证白名单内的自定义 URL Scheme 并将其显式 1 对 1 绑定到经过验证的目标软件包
        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. 阻止所有无法识别的 Scheme
        Log.w("WebViewDebug", "阻止了无法识别的 URL Scheme: $scheme")
        return true
    }

    // 用于子弹窗 WebView 的 UI 线程导航评估器,将 302 重定向绑定到授权会话
    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", "阻止了弹窗内部的子框架 HTTPS 导航")
                return true
            }
            if (!policy.isAllowedPopupUri(targetUri)) {
                Log.w("WebViewDebug", "阻止了不受信任的弹窗 HTTPS host 或 path 导航")
                return true
            }
            // 仅在初始加载或用户点击匹配白名单时在 UI 线程上授权会话
            if (isInitialTransportLoad || hasUserGesture) {
                onAuthorizedInitialSession()
                return false
            }
            // 仅对先前授权的弹窗会话允许有界的服务器端 302 重定向
            if (isRedirect && isAuthorizedPopupSession && canProceedPopupRedirect()) {
                return false
            }

            Log.w("WebViewDebug", "阻止了未授权的重定向或非手势弹窗导航")
            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", "畸形的 intent URI 语法")
            return true
        }

        val fallbackUrl = parsedIntent.getStringExtra("browser_fallback_url")
        parsedIntent.removeExtra("browser_fallback_url")

        // 1 对 1 绑定:提取目标 Scheme 并针对预期目标软件包进行原生验证
        val dataUri = parsedIntent.data ?: return true
        val targetScheme = dataUri.scheme?.lowercase() ?: return true
        val expectedPackage = policy.customSchemeTargetPackages[targetScheme] ?: run {
            Log.w("WebViewDebug", "阻止了带有未映射自定义 Scheme 的 intent: $targetScheme")
            return true
        }

        val rawPackage = parsedIntent.`package`
        if (rawPackage != expectedPackage) {
            Log.w("WebViewDebug", "阻止了 intent 软件包不匹配:期望 $expectedPackage")
            return true
        }

        // 立即拒绝网页指定的显式组件和选择器
        if (parsedIntent.component != null || parsedIntent.selector != null) {
            Log.w("WebViewDebug", "阻止了带有显式组件或选择器的 intent")
            return true
        }

        // 在调用带有 allowAnyComponent() 的 IntentSanitizer 之前临时清除经过验证的软件包
        // 以避免构建器互斥约束,同时严格拒绝不受信任的标志/额外参数。
        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 针对不允许的字段或标志抛出 SecurityException")
            return true
        } catch (e: IllegalArgumentException) {
            Log.w("WebViewDebug", "IntentSanitizer 拒绝了无效的 intent 参数")
            return true
        }

        // 重新绑定经过验证的目标软件包 + 宿主强制执行的类别 + 后净化断言
        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", "后净化 intent 断言失败")
            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", "阻止了不受信任或陷入死循环的回退 URL")
                }
            }
        } catch (e: SecurityException) {
            Log.w("WebViewDebug", "SecurityException 阻止了 intent 启动")
        }
        return true
    }

    private fun launchIntentSafely(view: WebView, intent: Intent) {
        try {
            launchWithContextSafety(view, intent)
        } catch (e: ActivityNotFoundException) {
            Log.i("WebViewDebug", "没有已安装的应用处理目标软件包/Scheme")
        } catch (e: SecurityException) {
            Log.w("WebViewDebug", "SecurityException 阻止了自定义 Scheme 启动")
        }
    }

    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. 生命周期管理的弹窗 WebChromeClient(严格的 UI 线程会话状态与无状态后台保护)
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 = "正在加载目标..."
        }
        popupRoot.addView(originBanner)

        // 下方的所有弹窗会话状态变量均严格在 UI 线程上读取和修改
        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 线程:拥有导航、重定向和会话授权状态
                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
                }

                // 后台 WebView IO 线程:严格无状态、只读策略检查。
                // 绝不修改 UI 线程会话状态;仅覆盖初始资源 URL(不覆盖后续的 302 跳数)。
                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", "在 shouldInterceptRequest 中阻止了未经批准的弹窗主框架请求")
                            childView.post { disposeActivePopup() }
                            return WebResourceResponse("text/plain", "utf-8", ByteArrayInputStream(ByteArray(0)))
                        }
                    }
                    return super.shouldInterceptRequest(childView, request)
                }

                // UI 线程:导航开始回退检查与来源显示(非预导航过滤器)
                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", "导航开始回退检查终止了未经批准的弹窗 URL")
                        childView.stopLoading()
                        disposeActivePopup()
                        return
                    }
                    isAuthorizedPopupSession = true
                    val scheme = uri.scheme?.lowercase() ?: "https"
                    val host = uri.host?.lowercase() ?: "未知"
                    originBanner.text = "来源: $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. 完整的宿主 Activity 注册与生命周期清理示例(在主 WebView 上启用 JavaScript)
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 {
                // 显式为需要 JS 重定向或 window.open() 的受信任落地页启用 JavaScript
                javaScriptEnabled = true
                allowFileAccess = false
                allowContentAccess = false
                // 仅在托管交互式弹窗容器时启用多窗口
                setSupportMultipleWindows(true)
            }
            webViewClient = safeClient
            webChromeClient = popupChromeClient
        }
        setContentView(webView)

        // 使用显式宿主包装器,而不是裸露的 webView.loadUrl()
        safeClient.loadNewNavigation(webView, "https://example.com/landing")
    }

    override fun onDestroy() {
        popupChromeClient.destroyPopups()
        (webView.parent as? ViewGroup)?.removeView(webView)
        webView.destroy()
        super.onDestroy()
    }
}

常见问题解答 (FAQ)

为什么即使用户安装了目标应用,Android WebView 仍然显示 net::ERR_UNKNOWN_URL_SCHEME?
当 Chromium 尝试在其网络栈上获取非 HTTP 自定义 URL Scheme 而不是将其转发给 Android 的 Activity Manager 时,就会出现此错误。请验证五个检查点:确认已分配自定义 `WebViewClient`;确保 `shouldOverrideUrlLoading(WebView, WebResourceRequest)` 对拦截的 Scheme 返回 `true`;确认 URI 结构和 1 对 1 目标软件包通过了您的白名单;验证 `startActivity(intent)` 执行干净(如果调用 `resolveActivity()`,则捕获 `ActivityNotFoundException` 或为 `targetSdk >= 30` 配置 `<queries>`);并确认目标应用的清单声明了带有 `CATEGORY_BROWSABLE` 的匹配 `<intent-filter>`。
为什么当应用直接调用 WebView loadUrl 时 shouldOverrideUrlLoading 未能触发?
根据 Android 框架设计,对于应用发起的 `webView.loadUrl()` 调用或 HTTP `POST` 导航,不会调用 `shouldOverrideUrlLoading`。它主要针对由网页内容、用户交互或支持的 HTTP 3xx 服务器重定向发起的导航。请从页面内的 DOM 交互或服务器响应触发测试重定向,并在审核应用发起的加载时使用显式宿主包装器(例如 `loadNewNavigation`)。
为什么带有自定义 Scheme 的 target blank 链接在 WKWebView 内部会静默失败?
当网页链接使用 `target="_blank"` 或 `window.open()` 时,WebKit 会创建一个新窗口导航请求,其中 `navigationAction.targetFrame` 为 `nil`。因为 `WKWebView` 不会自动打开新标签页,所以这些导航可能会静默失败,除非宿主应用在 `decidePolicyForNavigationAction` 中检测到 `targetFrame == nil`,并实现 `WKUIDelegate.webView(_:createWebViewWith:for:windowFeatures:)` 以在其统一导航策略下评估和路由请求。

总结与决策框架

解决 WebView 深度链接重定向故障需要将 WebView 引擎行为与宿主应用导航策略隔离。通过在 Chrome DevTools 或 Safari Web Inspector 中重现导航事件,将 Android 弹窗会话状态严格限制在 UI 线程中,同时将无状态初始请求筛查与会话授权的 302 重定向检查配对,强制执行故障关闭的 IntentSanitizer 白名单,并保护 iOS 通用链接回退免受陈旧的异步覆盖和重复代理启动的影响,工程团队可以减少破损的用户旅程并帮助防止客户端重定向漏洞。

在验证了容器级原生代理和回退路径后,工程团队还应使用诸如 OpoInstall 等平台验证全链路归因落地页和一键拉起路由链,以确认浏览器到 App 转换期间参数的完整保留。

实体术语表

术语 定义 相关实体 搜索意图角色
WebView 用于在移动应用内部渲染网页的嵌入式原生 UI 组件。 WebViewClient / WKWebView 信息型 / 技术型
自定义 URL Scheme (Custom URL Scheme) 启用外部导航进入原生屏幕的应用注册 URI 前缀(例如 myapp://)。 Intent.ACTION_VIEW 技术型 / 信息型
WKNavigationDelegate 允许宿主应用在 WKWebView 中接受、取消或重定向导航操作的 WebKit 协议。 decidePolicyForNavigationAction 技术型
WKUIDelegate 负责处理 WKWebView 中新窗口创建请求的 WebKit 协议。 createWebViewWith 技术型
WebResourceRequest 封装 URL、frame、HTTP 方法、重定向和手势元数据的 Android API 24+ 对象。 shouldOverrideUrlLoading 技术型
WebChromeClient 处理 JavaScript 对话框、进度和 onCreateWindow 的 Android WebView 回调接口。 WebViewTransport 技术型
IntentSanitizer 用于在分发前过滤或严格验证不受信任的 Intent 字段的 AndroidX Core 实用工具。 Intent 重定向防御 技术型 / 安全型
通用链接 (Universal Links) 将经过验证的网页域与已安装的 iOS 应用绑定的苹果 HTTPS 深度链接标准。 关联域名 (Associated Domains) 技术型 / 信息型
软件包可见性 (Package Visibility) Android 11+ (targetSdk >= 30) 操作系统过滤,限制宿主应用可以通过 PackageManager 查询哪些已安装的应用。 <queries> 清单标签 技术型
Intent URI 编码目标软件包、Scheme 和浏览器回退 URL 的结构化 Android URI (intent://)。 Intent.URI_INTENT_SCHEME 技术型

兼容性基线与验证状态

  • 预期兼容性目标:Android minSdk 24、compileSdk 34/35、targetSdk 34/35 (Android 14/15)、Android 16 (API 36) Intent 重定向加固上下文、androidx.core:core:1.9.0+ (IntentSanitizer);iOS 15.0–18.0(在 iOS 16.4+ 上门控 isInspectable)、Xcode 15/16、Swift 5.9/6.0。

  • 验证状态:

    • 静态 API 与规范审查:已针对官方 Android 开发者、AndroidX Core、苹果开发者、IETF RFC 3986 和 OWASP MASTG 规范完成审查。

    • 编译与物理设备验证:在此审查周期中尚未执行。团队必须在生产发布之前,编译并执行涵盖恶意初始弹窗 URL、跨域 302 链、连续 302 跳数、第三方 iframe 窗口创建、Android App Links (assetlinks.json)、iOS 关联域名(AASA 缓存)、陈旧异步通用链接取消、intent:// 回退链以及 ActivityNotFoundException 分发的物理设备回归测试。

参考资料

Share this article