DEV Community

Filip Němeček
Filip Němeček

Posted on

iOS: 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)
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (2)

Collapse
 
chaoscrafter profile image
Keith Ealanta

Very useful, thankyou.
Of course, Ive a special case where this doesnt work, and Id love your thoughts.
I want a headless wkwebview (or the webcontent part of it) but I can't use normal display objects.
The context is an apple widget to extend an app that uses webview, but widgets are limited and cant use wkwebview. I just want to use the webview to access the indeseddb instance of my page.
Any thoughts on how to do a completely detached webview, where I can run scripts and communicate with the app?
Im wondering if the webcontent component might make this viable, but Im not sure where the comms objects operate or if the webcontent object can be instantiated without wkwebview.
(I'll post more if I find out)

Collapse
 
ankit199 profile image
Ankit kumar shukla

hey i am facing issue related to wkwebview for ionic 3