You need to enable JavaScript to run this app.
导航

WKWebView

最近更新时间2024.03.29 17:41:10

首次发布时间2023.03.22 20:49:16

方案描述

如果您的 app 使用了 WKWebView,您可以:

  1. 通过 WKWebView 的私有 API 注册 scheme,保证 NSURLProtocol 可以拦截 WKWebView 中的请求。
  2. 根据您使用的网络库类型创建请求。
  3. 使用 WKWebView.loadRequest 加载请求。

前提条件

警告

对于没有在控制台添加的域名,HTTPDNS 服务端的解析会失败,您只能获得 Local DNS 服务器的解析结果。参见 添加需要解析的域名了解如何添加域名。

实现步骤

注意

为了演示需要,示例代码仅提供了集成方案中最基本的逻辑。移动解析 HTTPDNS 仅保证 HTTPDNS SDK 本身的 可用性。在生产环境下,您需要自行保证集成方案的健壮性。

  1. WKBrowsingContextController 中通过 registerSchemeForCustomProtocol 注册 scheme。然后,您需要使用 performSelector 匹配 NSURLProtocol。 这样,您就可以通过原生或自定义 NSURLProtocol 拦截请求。

    // 在 WKBrowsingContextController 中通过 registerSchemeForCustomProtocol 注册 scheme
    Class cls = NSClassFromString(@"WKBrowsingContextController");
    // 通过 NSSelectorFromString 获得 WKWebView 的私有 API,避免被 Apple 检查到使用私有 API
    SEL sel = NSSelectorFromString(@"registerSchemeForCustomProtocol:");
    if ([cls respondsToSelector:sel]) {
       // 匹配 NSURLProtocol 中 HTTP 和 HTTPS 的 scheme
       [cls performSelector:sel withObject:@"http"];
       [cls performSelector:sel withObject:@"https"];
    }
    
  2. 根据您的网络库场景,参考以下文档通过 NSURLSession 创建请求:

  3. 使用 WKWebView.loadRequest 加载请求。

    [self.wkWebView loadRequest:request];