Swift版 WKWebViewでJavaScript(Alert,Confirm,Prompt)の処理

  • 15
    いいね
  • 1
    コメント

Obj-C版はこちら
WKWebViewでJavaScript(Alert,Confirm,Prompt)の処理
http://qiita.com/ShingoFukuyama/items/5d97e6c62e3813d1ae98

Swift版がggっても出てこないということで、作成してみました。
WKWebViewの生成のあたりは省いていますのでそこは頑張ってください。

import UIKit
import WebKit

class WebViewController: UIViewController,WKNavigationDelegate,WKUIDelegate {

        .    
        .    
        .    

    // display alert dialog
    func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: () -> Void) {
        let alertController = UIAlertController(title: "", message: message, preferredStyle: .Alert)
        let otherAction = UIAlertAction(title: "OK", style: .Default) {
            action in completionHandler()
        }        
        alertController.addAction(otherAction)
        presentViewController(alertController, animated: true, completion: nil)
    }        

    // display confirm dialog
    func webView(webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: (Bool) -> Void) {   
        let alertController = UIAlertController(title: "", message: message, preferredStyle: .Alert)
        let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) {
            action in completionHandler(false)
        }        
        let okAction = UIAlertAction(title: "OK", style: .Default) {
            action in completionHandler(true)
        }        
        alertController.addAction(cancelAction)
        alertController.addAction(okAction)
        presentViewController(alertController, animated: true, completion: nil)
    }        

    // display prompt dialog
    func webView(webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: (String?) -> Void) {

        // variable to keep a reference to UIAlertController
        let alertController = UIAlertController(title: "", message: prompt, preferredStyle: .Alert)

        let okHandler: () -> Void = { handler in
            if let textField = alertController.textFields?.first {
                completionHandler(textField.text)
            } else { 
                completionHandler("")
            }        
        }        
        let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) {
            action in completionHandler("")
        }        
        let okAction = UIAlertAction(title: "OK", style: .Default) {
            action in okHandler()
        }        
        alertController.addTextFieldWithConfigurationHandler() { $0.text = defaultText }
        alertController.addAction(cancelAction)
        alertController.addAction(okAction)
        presentViewController(alertController, animated: true, completion: nil)
    }        
}