WKWebView is a powerful object for integrating the web into your apps. To support alerts a few WKWebView.uiDelegate callbacks need to be implemented. This post presents code examples for supporting various Javascript alerts in a WKWebView on iOS and macOS:

  1. WKWebView Javascript Alert Message on iOS
  2. WKWebView Javascript Confirm Action on iOS
  3. WKWebView Javascript Input Prompt on iOS
  4. WKWebView Javascript Alert Message on macOS
  5. WKWebView Javascript Confirm Action on macOS
  6. WKWebView Javascript Input Prompt on macOS

WKWebView UIDelegate

The WKWebView.uiDelegate protocol contains the methods necessary to support Javascript alerts in a WKWebView. Make sure to adhere to the WKWebView.uiDelegate or otherwise the delegate methods will not be called.

webKitView?.uiDelegate = self

WKWebView Javascript Alert Message on iOS

The webView(_:, runJavaScriptAlertPanelWithMessage:, initiatedByFrame:, completionHandler:) is called when window.alert("message") is called in Javascript. One implementation on iOS in Swift might use a UIAlertController to display the alert to the user.

func webView(_ webView: WKWebView, 
    runJavaScriptAlertPanelWithMessage message: String, 
    initiatedByFrame frame: WKFrameInfo, 
    completionHandler: @escaping () -> Void) {
    
    // Set the message as the UIAlertController message
    let alert = UIAlertController(
        title: nil,
        message: message,
        presentationStyle: .alert
    )

    // Add a confirmation action “OK”
    let okAction = UIAlertAction(
        title: “OK”,
        style: .default,
        handler: { _ in
            // Call completionHandler
            completionHandler()
        }
    )
    alert.addAction(okAction)

    // Display the NSAlert
    present(alert, animated: true, completion: nil)
}

WKWebView Javascript Confirm Action on iOS

The webView(_:, runJavaScriptConfirmPanelWithMessage:, initiatedByFrame:, completionHandler:) is called when window.confirm("message") is called in Javascript. One implementation on iOS in Swift might use a UIAlertController to display the confirmation to the user, calling completionHandler(true) if the user chose to confirm the action.

func webView(_ webView: WKWebView, 
    runJavaScriptConfirmPanelWithMessage message: String, 
    initiatedByFrame frame: WKFrameInfo, 
    completionHandler: @escaping (Bool) -> Void) {

    // Set the message as the UIAlertController message
    let alert = UIAlertController(
        title: nil,
        message: message,
        presentationStyle: .alert
    )

    // Add a confirmation action “OK”
    let okAction = UIAlertAction(
        title: “OK”,
        style: .default,
        handler: { _ in
            // Call completionHandler confirming the choice
            completionHandler(true)
        }
    )
    alert.addAction(okAction)

    // Add a cancel action “Cancel”
    let cancelAction = UIAlertAction(
        title: “Cancel”,
        style: .cancel,
        handler: { _ in
            // Call completionHandler cancelling the choice
            completionHandler(false)
        }
    )
    alert.addAction(cancelAction)

    // Display the NSAlert
    present(alert, animated: true, completion: nil)
}

WKWebView Javascript Input Prompt on iOS

The webView(_:, runJavaScriptTextInputPanelWithPrompt:, initiatedByFrame:, completionHandler:) is called when window.prompt("prompt", "default response") is called in Javascript. One implementation on iOS in Swift might use a UIAlertController to display a text field for user input, calling completionHandler with the user’s input text.

func webView(_ webView: WKWebView, 
    runJavaScriptTextInputPanelWithPrompt prompt: String, 
    defaultText: String?, 
    initiatedByFrame frame: WKFrameInfo, 
    completionHandler: @escaping (String?) -> Void) {
    
    // Set the prompt as the UIAlertController message
    let alert = UIAlertController(
        title: nil,
        message: message,
        presentationStyle: .alert
    )

    // Add a text field to the UIAlertController
    alert.addTextField() 

    // Add a confirmation action “Submit”
    let submitAction = UIAlertAction(
        title: “Submit”,
        style: .default,
        handler: { [unowned alert] _ in
            // Call completionHandler with the user input 
            let input = alert.textFields?.first
            completionHandler(input?.text)
        }
    )
    alert.addAction(submitAction)

    // Display the NSAlert
    present(alert, animated: true, completion: nil)
}

WKWebView Javascript Alert Message on macOS

The webView(_:, runJavaScriptAlertPanelWithMessage:, initiatedByFrame:, completionHandler:) is called when window.alert("message:) is called in Javascript. One implementation on macOS in Swift might use a NSAlert to display the alert to the user.

func webView(_ webView: WKWebView, 
    runJavaScriptAlertPanelWithMessage message: String, 
    initiatedByFrame frame: WKFrameInfo, 
    completionHandler: @escaping () -> Void) {
    
    // Set the message as the NSAlert text
    let alert = NSAlert()
    alert.informativeText = message
    alert.addButton(withTitle: "Ok")

    // Display the NSAlert
    alert.runModal()

    // Call completionHandler
    completionHandler()
}

WKWebView Javascript Confirm Action on macOS

The webView(_:, runJavaScriptConfirmPanelWithMessage:, initiatedByFrame:, completionHandler:) is called when window.confirm(:message") is called in Javascript. One implementation on macOS in Swift might use a NSAlert to display the confirmation to the user, calling completionHandler(true) if the user chose to confirm the action.

func webView(_ webView: WKWebView, 
    runJavaScriptConfirmPanelWithMessage message: String, 
    initiatedByFrame frame: WKFrameInfo, 
    completionHandler: @escaping (Bool) -> Void) {

    // Set the message as the NSAlert text
    let alert = NSAlert()
    alert.informativeText = message

    // Add a confirmation button “OK” 
    // and cancel button “Cancel”
    alert.addButton(withTitle: "OK")
    alert.addButton(withTitle: "Cancel")

    // Display the NSAlert
    let action = alert.runModal()

    // Call completionHandler with true only 
    // if the user selected OK (the first button)
    completionHandler(action == .alertFirstButtonReturn)
}

WKWebView Javascript Input Prompt on macOS

The webView(_:, runJavaScriptTextInputPanelWithPrompt:, initiatedByFrame:, completionHandler:) is called when window.prompt("prompt", "default response") is called in Javascript. One implementation on macOS in Swift might use a NSAlert to display a NSTextField for user input, calling completionHandler with the user’s input text.

func webView(_ webView: WKWebView, 
    runJavaScriptTextInputPanelWithPrompt prompt: String, 
    defaultText: String?, 
    initiatedByFrame frame: WKFrameInfo, 
    completionHandler: @escaping (String?) -> Void) {

    // Set the prompt as the NSAlert text
    let alert = NSAlert()
    alert.informativeText = prompt
    alert.addButton(withTitle: "Submit")

    // Add an input NSTextField for the prompt
    let inputFrame = NSRect(
        x: 0, 
        y: 0, 
        width: 300, 
        height: 24
    )

    let textField = NSTextField(frame: inputFrame)
    textField.placeholderString = ("Your input")
    alert.accessoryView = textField

    // Display the NSAlert
    alert.runModal()

    // Call completionHandler with 
    // the user input from textField
    completionHandler(textField.stringValue)
}

Show Javascript Alerts in a WKWebView on iOS and macOS in Swift

That’s it! Using the examples provided you can handle Javascript alerts in your iOS and macOS apps using WKWebView and Swift.