WKWebView 獲取JS端的console.log日志

主要思路: 1.重寫js的console.log方法。 2.iOS端在h5開始創(chuàng)建DOM樹的時候注入。

源代碼地址:https://github.com/housenkui/WKWebView-Console

您的星星,是我最大的鼓勵。O(∩_∩)O謝謝

#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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容