Swift WebView Alert沒有顯示 無法顯示 無法彈窗

WebView Alert 無法顯示?

iOS為什麼使用WebView Alert沒辦法顯示? webView開啟網站後javascript alert在iOS上就是沒作用
如果你想到讓他彈出來
就要讓他轉為原生alert

1. 設置 webView

let webView = WKWebView(frame: CGRect(x: 0, y: self.view.frame.size.height, width: self.view.frame.size.width, height: self.view.frame.size.height))
webView.uiDelegate = self
self.view.addSubview(webView)
let url = URL(string: "https://www.google.com/")
webView.load(URLRequest(url: url!))

2. Delegate 添加

class HomeViewController: BaseViewController, WKUIDelegate {

3. WKWebView監聽

將監聽到的JavaScriptAlert事件
轉化為iOS原生的Alert

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()
    }))

    self.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)
    }))

    self.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: .alert)

    alertController.addTextField { (textField) in
        textField.text = defaultText
    }
}

WebView Alert 無法顯示

Swift更多文章

Swift 彈出視窗 AlertController 的使用方法 💥

Swift 判斷螢幕方向 📱

Swift Core Data 實現 💾🔥

Swift UISegmentedControl 💻分段控制器!

Swift 實現抽屜效果 🧹


參考連結:
ios webview alert彈窗不顯示網址解決辦法- IT閱讀
iOS WKWebView沒有顯示javascript alert()對話框- iOS
WKWebView下js的alert(),confirm(),prompt()方法无法正常执行

Categorized in: