使用WKWebView的時候會出現明明自己做的一些頁面有提示框, 為什么使用別人的頁面提示框總是不顯示, 其實很大部分原因是因為該提示框是通過JS調用的, 需要實現WKUIDelegate來進行監聽
// MARK: - WKUIDelegate // 監聽通過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) } // 監聽JS調用輸入框 func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) { // 類似上面兩個方法 }
這里需要注意, completionHandler一定要調用, 否則會出錯!