iOS把vConsole注入到wkwebview
2021-04-07 本文已影响0人
不要和哥闹
1、新建vconsole.js,将https://cdn.bootcss.com/vConsole/3.2.2/vconsole.min.js
或者http://wechatfe.github.io/lib/vconsole/3.4.0/vconsole.min.js
这个链接打开,将内容全部复制到vconsole.js里面
在vconsole.js里面最下面再加上这句话
let vConsole = new VConsole();
console.log("Hello World");
2、第一种注入方法,只注入当前webview
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
WKUserContentController * wkUController = [[WKUserContentController alloc] init];
config.userContentController = wkUController;
NSString *path = [[NSBundle mainBundle]pathForResource:@"vconsole.js" ofType:nil];
NSString *filename = [[NSString alloc]initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
WKUserScript *script = [[WKUserScript alloc] initWithSource:filename injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
[wkUController addUserScript:script];
WKWebView *webView = [[WKWebView alloc]initWithFrame:[UIScreen mainScreen].bounds configuration:config];
[self.view addSubview:webView];
//1.网络
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.qq.com/"]];
[webView loadRequest:request];
第二种注入方法,全局注入
@interface WKWebViewConfiguration (VConsole)
@end
@implementation WKWebViewConfiguration (VConsole)
+ (void)load {
Method origIMP = class_getInstanceMethod(self, @selector(setUserContentController:));
Method hookIMP = class_getInstanceMethod(self, @selector(setHookUserContentController:));
method_exchangeImplementations(origIMP, hookIMP);
}
- (void)setHookUserContentController:(WKUserContentController *)userContentController {
NSString *path = [[NSBundle mainBundle]pathForResource:@"vconsole.js" ofType:nil];
NSString *filename = [[NSString alloc]initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
WKUserScript *script = [[WKUserScript alloc] initWithSource:filename injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
[userContentController addUserScript:script];
[self setHookUserContentController:userContentController];
}
@end