JS端代码不做任何改变,所有代码写于native端。
主要思路: 1.重写js的console.log方法。 2.iOS端在h5开始创建DOM树的时候注入。
#import "SKWebView.h"
@interface WKWebView ()
@end
@implementation SKWebView
- (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration*)configuration {
if(self= [superinitWithFrame:frameconfiguration:configuration])
{
WKUserContentController *userCC = configuration.userContentController;
[userCCaddScriptMessageHandler:self name:@"log"];
}
return self;
}
- (void)showConsole {
NSString *jsCode = @"console.log = (function(oriLogFunc){\
return function(str)\
{\
window.webkit.messageHandlers.log.postMessage(str);\
oriLogFunc.call(console,str);\
}\
})(console.log);";
[self.configuration.userContentController addUserScript:[[WKUserScript alloc] initWithSource:jsCode injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES]];
}
- (void)userContentController:(WKUserContentController*)userContentController didReceiveScriptMessage:(WKScriptMessage*)message {
NSLog(@"%@",NSStringFromSelector(_cmd));
NSLog(@"%@",message.body);
}
源代码地址:https://github.com/housenkui/WKWebView-Console
您的星星,是我最大的鼓励。O(∩_∩)O谢谢