UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to control the user interface of a WKWebView using WKUIDelegate

Swift version: 5.6

Paul Hudson    @twostraws   

By default WKWebView works sort of like Safari, albeit in a single view rather than having tabs. If you want something more advanced – being able to monitor opening and closing windows, override behavior for JavaScript user interface, and so on – then the WKUIDelegate protocol is for you.

First, make your view controller conform to it by adding WKUIDelegate to its list of protocols. Second, assign your view controller to the uiDelegate property of your web view:

yourWebView.uiDelegate = self

Finally, implement whichever of the optional methods of WKUIDelegate takes your interest. For example, you can make WKWebView show a custom alert controller when any web page uses the alert() JavaScript function:

func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
    let ac = UIAlertController(title: "Hey, listen!", message: message, preferredStyle: .alert)
    ac.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
    present(ac, animated: true)
    completionHandler()
}

There’s also runJavaScriptConfirmPanelWithMessage for showing confirm and deny UI, runJavaScriptTextInputPanelWithPrompt for requesting user text input, and so on.

Note: You must call the completion handler. JavaScript’s alerts are blocking, which means JavaScript execution will not continue until the alert finishes. As a result, WebKit will complain if you don’t let it know when you’re done.

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS 10.0

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.