import UIKit
import WebKit
import SafariServices
final class ViewController: UIViewController {
@IBOutlet private weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.uiDelegate = self
loadLocalHTML()
}
func loadLocalHTML() {
guard let path: String = Bundle.main.path(forResource: "test", ofType: "html") else { return }
let localHTMLUrl = URL(fileURLWithPath: path, isDirectory: false)
webView.loadFileURL(localHTMLUrl, allowingReadAccessTo: localHTMLUrl)
}
}
extension ViewController: WKUIDelegate {
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
let alertController = UIAlertController(title: "", message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
completionHandler(false)
}
let okAction = UIAlertAction(title: "OK", style: .default) { _ in
completionHandler(true)
}
alertController.addAction(cancelAction)
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: { _ in
completionHandler()
}
)
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script language="javascript" type="text/javascript">
function OnButtonClick() {
if( confirm("Go To Apple.com?") ) {
window.location.href = "https://www.apple.com/";
}
else {
alert("Stop!");
}
}
</script>
</head>
<body>
<input type="button" value="Go To Apple.com" onclick="OnButtonClick();"/><br/>
<br />
<div id="output"></div>
</body>
</html>