alert() not working in WKWebview evaluateJavaScript()

前端 未结 3 1154
执念已碎
执念已碎 2021-01-04 04:04

I don\'t why my question is marked as duplicate of this one, first I execute javascript code with evaluateJavaScript as the question title shows which it\'s

3条回答
  •  借酒劲吻你
    2021-01-04 04:28

    It's my fault here. I've not much experience with WKWebview. I've experience with android's XWalkview, and there execute alert needn't to implement alert with java code. So here I also missed thought I don't need to implementation the alert delegate with swift.

    From answer of Onato, I learned how swift execute the alert prompt and confirm, I lost the implementation of these delegate. So I refer to this answer, add below implementation, everything works.

    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo,
                 completionHandler: @escaping () -> Void) {
    
        let alertController = UIAlertController(title: nil, message: message, preferredStyle: .actionSheet)
        alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
            completionHandler()
        }))
    
        present(alertController, animated: true, completion: nil)
    }
    
    
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo,
                 completionHandler: @escaping (Bool) -> Void) {
    
        let alertController = UIAlertController(title: nil, message: message, preferredStyle: .actionSheet)
    
        alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
            completionHandler(true)
        }))
    
        alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in
            completionHandler(false)
        }))
    
        present(alertController, animated: true, completion: nil)
    }
    
    
    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo,
                 completionHandler: @escaping (String?) -> Void) {
    
        let alertController = UIAlertController(title: nil, message: prompt, preferredStyle: .actionSheet)
    
        alertController.addTextField { (textField) in
            textField.text = defaultText
        }
    
        alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
            if let text = alertController.textFields?.first?.text {
                completionHandler(text)
            } else {
                completionHandler(defaultText)
            }
        }))
    
        alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in
            completionHandler(nil)
        }))
    
        present(alertController, animated: true, completion: nil)
    }
    

提交回复
热议问题