Mike Purcell Mike Purcell - 1 month ago 45
iOS Question

WKWebView - Javascript Confirm and Alert not working

I am using WKWebView to open up example.com, and on there I have a test link which is supposed to open up a JS alert, but I can't get it to display on the device, it only works if I view the site from browser.

I am using WKUIDelegate, and added this piece of code to the ViewController.swift file:

func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: (() -> Void)) {

NSLog("Hello")
}


I don't see anything in the XCode console when I click the link that spawns the JS alert.

What am I missing?

Answer

You also need to set the UIDelegate on the WKWebView.

public override func viewDidLoad() {
    super.viewDidLoad()

    self.wkWebView = WKWebView(frame: self.view.bounds, 
                       configuration: WKWebViewConfiguration())
    self.wkWebView?.UIDelegate = self
    self.view.addSubview(self.wkWebView!)

    let URL = NSURL(string: "http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert")!
    self.wkWebView!.loadRequest(NSURLRequest(URL: URL))
}

public func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: (() -> Void)) {
    print(message)
    completionHandler()
}
Comments