美文网首页
iOS把vConsole注入到wkwebview

iOS把vConsole注入到wkwebview

作者: 不要和哥闹 | 来源:发表于2021-04-07 10:02 被阅读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
    

    相关文章

      网友评论

          本文标题:iOS把vConsole注入到wkwebview

          本文链接:https://www.haomeiwen.com/subject/lkbykltx.html