81 lines
3.0 KiB
Objective-C
81 lines
3.0 KiB
Objective-C
//
|
|
// GDWebPageHookService.m
|
|
// DESThreeTest
|
|
//
|
|
// Created by Qwerdf on 2025/10/24.
|
|
// Copyright © 2025 zhang alan. All rights reserved.
|
|
//
|
|
|
|
#import "GDWebPageHookService.h"
|
|
|
|
@implementation GDWebPageHookService
|
|
|
|
#pragma mark - 初始化
|
|
- (instancetype)initWithSchemeTask:(id<WKURLSchemeTask>)task {
|
|
if (self = [super init]) {
|
|
_schemeTask = task;
|
|
}
|
|
return self;
|
|
}
|
|
|
|
#pragma mark - GDWebCustomURLSchemeProtocol
|
|
+ (BOOL)canService:(id<WKURLSchemeTask>)task {
|
|
// 处理需要钩子的请求(如包含 "/api/hook" 的接口)
|
|
NSString *urlString = task.request.URL.absoluteString;
|
|
return [urlString containsString:@"/api/hook"];
|
|
}
|
|
|
|
- (void)startLoading:(void (^)(void))completion {
|
|
self.completion = completion;
|
|
NSURLRequest *request = self.schemeTask.request;
|
|
|
|
// 1. 发起原始网络请求
|
|
self.dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
|
|
if (error) {
|
|
// 网络错误,直接返回给网页
|
|
[self.schemeTask didFailWithError:error];
|
|
if (completion) completion();
|
|
return;
|
|
}
|
|
|
|
// 2. 钩子逻辑:修改响应数据(示例:给 API 响应添加自定义字段)
|
|
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
|
|
NSMutableDictionary *headers = [httpResponse.allHeaderFields mutableCopy];
|
|
// 允许网页接收修改后的数据(处理跨域)
|
|
headers[@"Access-Control-Allow-Origin"] = @"*";
|
|
|
|
// 若为 JSON 响应,修改内容
|
|
NSData *modifiedData = data;
|
|
if ([httpResponse.MIMEType containsString:@"application/json"] && data) {
|
|
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
|
|
if (json) {
|
|
json[@"_injected_by_native"] = @"true"; // 注入自定义字段
|
|
modifiedData = [NSJSONSerialization dataWithJSONObject:json options:0 error:nil];
|
|
}
|
|
}
|
|
|
|
// 3. 构造修改后的响应并返回给网页
|
|
NSHTTPURLResponse *modifiedResponse = [[NSHTTPURLResponse alloc] initWithURL:httpResponse.URL
|
|
statusCode:httpResponse.statusCode
|
|
HTTPVersion:@"HTTP/1.1"
|
|
headerFields:headers];
|
|
[self.schemeTask didReceiveResponse:modifiedResponse];
|
|
[self.schemeTask didReceiveData:modifiedData];
|
|
[self.schemeTask didFinish];
|
|
|
|
// 调用完成回调
|
|
if (completion) completion();
|
|
}];
|
|
[self.dataTask resume];
|
|
}
|
|
|
|
- (void)stopLoading {
|
|
// 停止网络请求
|
|
[self.dataTask cancel];
|
|
self.dataTask = nil;
|
|
self.schemeTask = nil;
|
|
if (self.completion) self.completion();
|
|
}
|
|
|
|
@end
|