简体   繁体   中英

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

Javascript popups are not working for me with WebKit.

In Safari (on OSX) this document will create the expected alert and confirm popups. But with my WebKit instance running on IOS simulator or device the popups are not displayed and the confirm function 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>

I am using Xcode 7.3, compiling for IOS 9.3. The info.plist has "AppTransportSecurity" to "Allow arbitrary HTML" .

This is the code view controller code where I instantiate the web view:

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)

  }
}

From this answer

You must the webview delegate:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM