Skip to content

Instantly share code, notes, and snippets.

@dakeshi
Last active March 21, 2016 07:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dakeshi/f6bae5e8a6f915581df3 to your computer and use it in GitHub Desktop.
Save dakeshi/f6bae5e8a6f915581df3 to your computer and use it in GitHub Desktop.
WKUIDelegate provides native UI elements instead of webpage. For example, you can display UIAlertController in response to JavaScript confirm function. You need to confirm WKUIDelegate protocol before using it.
// confirm : WKUIDelegate protocol
webView.UIDelegate = self
…..
** javascript popup box test
// let alert_box_url = "http://www.w3schools.com/js/tryit.asp?filename=tryjs_alert"
// let confirm_box_url = "http://www.w3schools.com/js/tryit.asp?filename=tryjs_confirm"
// usage : webView.loadRequest(NSURLRequest(URL: NSURL(string:alert_box_url)!))
// JS alert box
func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: (() -> Void)) {
let alertController = UIAlertController(title: "Notice", message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: { action in
completionHandler()
}))
self.presentViewController(alertController, animated: true, completion: nil)
}
// JS confirm box.
// Display alertView through UIAlertController instead of JS popup
// You don't need to write confirm logic. It's for the webpage.
// ref : https://github.com/qmihara/WebKitDemo/blob/master/WebKitDemo/WebViewController.swift
func webView(webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: (Bool) -> Void) {
#if DEBUG
print("JAVA Script Confirm")
#endif
let alertController = UIAlertController(title: webView.URL?.host, message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { action in
completionHandler(false)
}))
alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: { action in
completionHandler(true)
}))
self.presentViewController(alertController, animated: true, completion: nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment