iOS app中WKWebView如何连接safari调试

598 阅读1分钟

1.WKWebView设置如下:

webView.isInspectable = true

2.打开MacSafari浏览器配置 ,勾选底部的显示网页开发者功能,如图:

截屏2024-07-06 08.00.27.png

3.用模拟器或则真机运行程序后,打开safari的菜单栏的开发,选择设备,找到当前运行的程序,点击后,会开启Safari网页检查器功能

截屏2024-07-06 08.06.45.png

4.例如在webView中加载一个简单的html网页

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>HELLO WORLD</h1>
    <script>
        function hello() {
            console.log('hello world')
        }
    </script>
</body>
</html>

利用WKWebView调用网页中的js方法

webView.evaluateJavaScript("hello()") { value, err in
    print(err ?? "nil")
}

会在Safari网页检查器的控制台日志上打印出hello world

截屏2024-07-06 08.20.49.png