Swift 转 Objective-C: WKWebView 中使用 JavaScript 的 console.log
Swift 转 Objective-C: WKWebView 中使用 JavaScript 的 console.log
本文演示如何在 Swift 和 Objective-C 中使用 WKWebView,并通过自定义 console.log 函数将 JavaScript 中的日志信息传递到 Objective-C 代码中。
Swift 代码
let web = WKWebView.init(frame: CGRect.init(x: 0, y: 100, width: view.bounds.size.width, height: view.bounds.size.height - 100))
let js = '''
console.log = (function(oriLogFunc){
return function(str){
oriLogFunc.call(console,str);
//这里,在执行自定义console.log的时候,将str传递出去。
window.webkit.messageHandlers.log.postMessage(str);
}
})(console.log);
'''
let script = WKUserScript.init(source: js, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: false)
web.configuration.userContentController.addUserScript(script)
web.configuration.userContentController.add(self, name: 'log')
Objective-C 代码
#import <WebKit/WebKit.h>
WKWebView *web = [[WKWebView alloc] initWithFrame:CGRectMake(0, 100, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - 100)];
NSString *js = @'console.log = (function(oriLogFunc){
return function(str){
oriLogFunc.call(console,str);
window.webkit.messageHandlers.log.postMessage(str);
}
})(console.log);';
WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[web.configuration.userContentController addUserScript:script];
[web.configuration.userContentController addScriptMessageHandler:self name:@'log'];
说明
- 代码中使用了一个自定义的
console.log函数,该函数会在执行原始的console.log后,将日志信息通过window.webkit.messageHandlers.log.postMessage(str)发送到 Objective-C 代码中。 - Objective-C 代码需要实现
WKScriptMessageHandler协议,并处理log消息。
总结
本文演示了如何在 Swift 和 Objective-C 中使用 WKWebView,并通过自定义 console.log 函数将 JavaScript 中的日志信息传递到 Objective-C 代码中。这种方法可以方便地调试和跟踪 JavaScript 代码中的执行情况。
原文地址: https://www.cveoy.top/t/topic/qzmQ 著作权归作者所有。请勿转载和采集!