javascript 在 IOS 9 中警告和确认弹出窗口不适用于 Webkit

javascript alert and confirm popups not working with Webkit in IOS 9

Javascript 弹出窗口不适用于我的 WebKit。

在 Safari(在 OSX)中,本文档将创建预期的警告和确认弹出窗口。但是在 IOS 模拟器或设备上,我的 WebKit 实例 运行 不会显示弹出窗口,并且确认功能 returns false.

<!DOCTYPE html>
<html>
<body>

    <p id="check3"></p>

    <script>
        alert("alert 1");

        function check3() {
            return(confirm("Confirm?"));
        }
    </script>

    <button type="button"
        onclick="document.getElementById('check3').innerHTML = check3()">
        Check 3</button>

</body>
</html>

我正在使用 Xcode 7.3,为 IOS 9.3 编译。 info.plist"AppTransportSecurity""Allow arbitrary HTML"

这是我实例化 Web 视图的代码视图控制器代码:

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

  @IBOutlet weak var wv: UIView!

  var webView : WKWebView?

  override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(true)

    let webViewCfg = WKWebViewConfiguration()
    webViewCfg.preferences.javaScriptEnabled = true;
    webViewCfg.preferences.javaScriptCanOpenWindowsAutomatically = true
    webView = WKWebView.init(frame:wv.bounds, configuration: webViewCfg)

    self.wv.addSubview(webView!)

    webView!.navigationDelegate = self

    let path = getBundlePath("js1.html")
    let targetFileURL = NSURL(fileURLWithPath: path!, isDirectory: false)
    webView!.loadFileURL(targetFileURL, allowingReadAccessToURL: targetFileURL)

  }
}

由此answer

您必须将 webview 委托:

// MARK: WKUIDelegate methods
func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: (() -> Void)) {
    print("webView:\(webView) runJavaScriptAlertPanelWithMessage:\(message) initiatedByFrame:\(frame) completionHandler:\(completionHandler)")

    let alertController = UIAlertController(title: frame.request.URL?.host, message: message, preferredStyle: .Alert)
        alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: { action in
            completionHandler()
    }))
    self.presentViewController(alertController, animated: true, completion: nil)
}