Swift WKWebView js交互的一些问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014128241/article/details/88866153

网页JS弹窗使用

 // 监听通过JS调用警告框
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
            completionHandler()
        }))
        self.present(alert, animated: true, completion: nil)
    }
    
    // 监听通过JS调用提示框
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
            completionHandler(true)
        }))
        alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in
            completionHandler(false)
        }))
        self.present(alert, animated: true, completion: nil)
    }

事件的处理

 let preferences = WKPreferences()
        preferences.javaScriptEnabled = true
        let configuration = WKWebViewConfiguration()
        configuration.preferences = preferences
        configuration.selectionGranularity = WKSelectionGranularity.character
        configuration.userContentController = WKUserContentController()
        // 给webview与swift交互起名字,webview给swift发消息的时候会用到
        configuration.userContentController.add(self, name: "close")
        
        
        webview = WKWebView(frame: CGRect(x: 0,
                                          y: 0,
                                          width: kScreenWidth,
                                          height: kScreenHeight - kNavBarHeight ),
                            configuration: configuration)

// 代理里面还有这些
 func userContentController(_ userContentController: WKUserContentController,
                               didReceive message: WKScriptMessage) {
        ///在控制台中打印html中console.log的内容,方便调试
       // let body = message.body
        if message.name == "close" {
          self.navigationController?.popViewController(animated: true)
        }
    
    }


猜你喜欢

转载自blog.csdn.net/u014128241/article/details/88866153