美文网首页
iOS解决WKWebView下alert(),confirm()

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

作者: 東玖零 | 来源:发表于2022-04-19 14:45 被阅读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)
    }
    

    相关文章

      网友评论

          本文标题:iOS解决WKWebView下alert(),confirm()

          本文链接:https://www.haomeiwen.com/subject/uivsertx.html