WKWebview 사용시 웹 자바스크립트의 log consol을 XCode Consol에서 출력해서 확인가능함.
Web Consol Log Call Injection
- Safari 디버깅시 해제해야 브라우저 콘솔에 파일명 및 라인등 정보가 정상적으로 노출됨.
- 앱개발시 XCode 콘솔에서 확인해야되는 경우만 적용 할것
let contentController = WKUserContentController()
contentController.add(self, name: WebMessageHandler.ios_javascript.rawValue)
//Web Consol Log Call Injection
contentController.add(self, name: WebMessageHandler.consol_log.rawValue)
let logConsole = """
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
function log(emoji, type, args) {
window.webkit.messageHandlers.\(WebMessageHandler.consol_log.rawValue).postMessage(
`${emoji} JS ${type}: ${Object.values(args)
.map(v => typeof(v) === "undefined" ? "undefined" : typeof(v) === "object" ? JSON.stringify(v, getCircularReplacer()) : v.toString())
.map(v => v.substring(0, 3000)) // Limit msg to 3000 chars
.join(", ")}`
)
}
let originalLog = console.log;
let originalWarn = console.warn;
let originalError = console.error;
let originalDebug = console.debug;
console.log = function() { log("📗", "log", arguments); originalLog.apply(null, arguments); };
console.warn = function() { log("📙", "warning", arguments); originalWarn.apply(null, arguments); };
console.error = function() { log("📕", "error", arguments); originalError.apply(null, arguments); };
console.debug = function() { log("📘", "debug", arguments); originalDebug.apply(null, arguments); };
window.addEventListener("error", function(e) {
log("💥", "Uncaught", [`${e.message} at ${e.filename}:${e.lineno}:${e.colno}`])
})
"""
let script = WKUserScript(source: logConsole, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
contentController.addUserScript(script)
let config = WKWebViewConfiguration()
config.processPool = processPool!
config.preferences.javaScriptCanOpenWindowsAutomatically = true
if #available(iOS 14.0, *) {
config.defaultWebpagePreferences.allowsContentJavaScript = true
} else {
config.preferences.javaScriptEnabled = true
}
// WKUserContentController WebView 연결
config.userContentController = contentController
// WKWebView 생성
webView = WKWebView(frame: .init(), configuration: config)
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
let handlerName = WebMessageHandler(rawValue: message.name)
// Scheme 및 JS -> Native 구분
switch handlerName {
case .consol_log:
log(direction: .WEB_CONSOL, ofType: self, datas: message.frameInfo.request.url!, message.body)
default:
break;
}
}'Swift > WKWebview' 카테고리의 다른 글
| [Swift] 사파리 브라우저 WebView 디버깅 설정(IOS 16.4 이상) (0) | 2024.05.27 |
|---|---|
| [SWIFT]Custom WKWebView version 1.0 (0) | 2023.07.19 |
| [SWIFT]Javascript (JS <-> Native)/ Custom Scheme 연동 V2 (0) | 2023.06.07 |
| [SWIFT]웹뷰의 보여지는 화면 스크린샷 이미지 생성 (0) | 2023.05.08 |
| [SWIFT]WKWebview 탭 제스쳐 적용 (0) | 2023.04.24 |