WKWebView注入VConsole.js
1.VConsoleInit.js
//VConsoleInit.js var a = function run() { var head = document.getElementsByTagName('head')[0]; var scripts = head.getElementsByTagName('script'); var found = 0; for (var i = 0; i < scripts.length; i++) { if (scripts[i].src == "https://unpkg.com/vconsole/dist/vconsole.min.js") { found = 1; console.log("have found vconsole script"); break } } if (found == 0) { console.log("add vconsole script"); var tr = document.createElement("script"); tr.src = "https://unpkg.com/vconsole/dist/vconsole.min.js"; head.appendChild(tr) } else { console.log("not add vconsole script") } }();
2.VConsoleAdd.js
//VConsoleAdd.js
var b = function run() { var head = document.getElementsByTagName('head')[0]; var scripts = head.getElementsByTagName('script'); var found = 0; for (var i = 0; i < scripts.length; i++) { if (scripts[i].innerHTML == "var vConsole = new window.VConsole();") { found = 1; console.log("have found vconsole object"); break } } if (found == 0) { console.log("add vconsole object"); var tb = document.createElement("script"); tb.type = "text/javascript"; tb.innerHTML = "var vConsole = new window.VConsole();"; head.appendChild(tb) } else { console.log("not add vconsole object") } }();
3.注入远程JS
//远程加载VConsole.js NSString *path = [[NSBundle mainBundle] pathForResource:@"VConsoleInit" ofType:@"js"]; NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error]; if (!error) { [self.contentWebView evaluateJavaScript:jsCode completionHandler:^(id data, NSError * error) { if(error){ NSLog(@"error:%@",[error description]); } }]; } else { NSLog(@"error %@",error); }
4.注入控制台
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ NSError *error = nil; NSString *path = [[NSBundle mainBundle] pathForResource:@"VConsoleAdd" ofType:@"js"]; NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error]; if (!error) { [self.contentWebView evaluateJavaScript:jsCode completionHandler:^(id data, NSError * error) { if(error){ NSLog(@"error:%@",[error description]); } }]; } else { NSLog(@"error %@",error); } });