iOS解决WKWebView下alert(),confirm()

2022-04-19  本文已影响0人  東玖零

原因:由于安全机制,WKWebView默认对JavaScript下alert(),confirm(),prompt()做了拦截,如果想正常使用,需要实现其三个代理方法。

1.设置代理

wkWebview.uiDelegate = self

2.解决alert方法

func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
   let vc = UIAlertController(title: "温馨提示", message: message, preferredStyle: .alert)
   vc.addAction(UIAlertAction(title: "确定", style: .default) { ac in
      completionHandler()
   })
   self.present(vc, animated: true, completion: nil)
}

3.解决confirm

func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
   let vc = UIAlertController(title: "温馨提示", message: message, preferredStyle: .alert)
   vc.addAction(UIAlertAction(title: "确定", style: .default) { ac in
            completionHandler(true)
   })
   vc.addAction(UIAlertAction(title: "取消", style: .cancel) { ac in
            completionHandler(false)
   })
   self.present(vc, animated: true, completion: nil)
}

4.解决prompt

func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
   let vc = UIAlertController(title: "温馨提示", message: prompt, preferredStyle: .alert)
   vc.addTextField { tf in
     tf.text = defaultText
   }
   vc.addAction(UIAlertAction(title: "确定", style: .default) { ac in
      completionHandler(vc.textFields?[0].text)
   })
   vc.addAction(UIAlertAction(title: "取消", style: .cancel) { ac in
   })
   self.present(vc, animated: true, completion: nil)
}
上一篇下一篇

猜你喜欢

热点阅读