Using WKWebView in headless mode

This is another short post about using `WKWebView`. Yet another useful use case can be to run `WKWebView` in the background, meaning user does not see it on the screen.

At first this can seem super easy. You will just create instance of WKWebView and work with it, right? Well, sort of. But there si something you need to be aware of.

Btw I am using the term headless, because this commonly used when working with webViews in background. so you have easier time Googling

WKWebView is optimized to not use too much resources when user is not directly interacting with it. It can detect this via its parent property to check whether it is part of the current view controller.

I found this out when my JavaScript code wasn’t working as expected in headless mode but worked perfectly fine when I had another WKWebView in the normal foreground mode.

Fortunately there is pretty easy solution. You can create instance with zero size frame and set it as a subview of main window of your application. Like this:

let webView = WKWebView(frame: CGRect.zero)
UIApplication.shared.windows.first?.addSubview(webView)

And now WKWebView is working as expected.

Note: Since iOS 13, there is now array windows of type UIWindow available via UIApplication.shared because apps can work with multiple windows. In the old templates we were dealing only with window property.

Uses: Xcode 11 & Swift 5