前提:一般情況下,對(duì)于網(wǎng)頁中javascript中輸出的log,是不會(huì)在XCode的控制臺(tái)輸出的,為了調(diào)試方便,更加清楚的獲取到j(luò)avascript中的log,需要讓js中的log也顯示在XCode的控制臺(tái)中。
具體解決方案:重寫js中的console.log
方法,在重寫的方法中觸發(fā)調(diào)用原生方法,將log的輸出內(nèi)容傳遞出去。
代碼實(shí)現(xiàn):
1.創(chuàng)建wkwebview,并在開始加載時(shí)注入一段js,該段js為重寫的console.log
方法。
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);
//這里,在執(zhí)行自定義console.log的時(shí)候,將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")
- 實(shí)現(xiàn)
WKScriptMessageHandler
代理方法,在代理方法中根據(jù)name
執(zhí)行輸出。
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "log" {
print(message.body)
}
}
3.測(cè)試,編寫一段js代碼,放入一個(gè)html文件中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
.triangle1{
width: 100;
height: 100;
background-color: red;
display: flex;
}
</style>
<script type="text/javascript">
function change() {
console.log('hello world');
}
</script>
</head>
<body>
<div class="triangle1" onclick="change()">jinsongpei</div>
</body>
</html>
4.運(yùn)行,測(cè)試代碼。
image.png
可以看到,控制臺(tái)輸出了log。