WKWebKit javascript execution when not attached to a view hierarchy WKWebKit javascript execution when not attached to a view hierarchy ios ios

WKWebKit javascript execution when not attached to a view hierarchy


Having run into the same problem, I never found any solution except to add the WKWebView to the view hierarchy and move it offscreen with AutoLayout. Fortunately, this workaround does work reliably.


I had exactly the same issue and have solved it with UIStackView. I created StackNavigationController, minimalistic drop-in replacement for UINavigationController, which basically adds new views to stack, while hiding all of them but the last one. Therefore, all views are still in hierarchy, executing and loading, but only the last one is visible. No animations, lots of missing API, feel free to build on that.

public class StackNavigationController: UIViewController {    private(set) var viewControllers: [UIViewController] = []    private var stackView: UIStackView { return view as! UIStackView }    override public func loadView() {        let stackView = UIStackView()        stackView.axis = .vertical        stackView.distribution = .fillEqually        view = stackView    }    func pushViewController(_ viewController: UIViewController, animated: Bool) {        let previousView = stackView.arrangedSubviews.last        viewControllers.append(viewController)        stackView.addArrangedSubview(viewController.view)        previousView?.isHidden = true    }    func popToRootViewController(animated: Bool) {        while stackView.arrangedSubviews.count > 1 {            stackView.arrangedSubviews.last?.removeFromSuperview()            viewControllers.removeLast()        }        stackView.arrangedSubviews.first?.isHidden = false    }}

My story:

  1. I have a UINavigationController with WKWebView(1) as root view
  2. WKWebView(1) has a hyperlink with target: _blank parameter set
  3. After tapping the link, I catch WKUIDelegate's webView(_:didRequestNewWebView:) and push another WKWebView(2) onto UINavigationController
  4. WKWebView(2) performs a request to server
  5. Server responds with JavaScript message to WKWebView(1)
  6. I never get the message, because WKWebView(1) is halted