alert() not working in WKWebview evaluateJavaScript()
There is a working example in this answer. It seems you mightn't have implemented the WKUIDelegate method correctly.
First of all you need to implement the required WKUIDelegate methods, in your case you need to implement:
optional func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void){ // parameter **message** will hold your actual alert message. // Write Your Customised code to display the alert message}
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)}