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:
- I have a
UINavigationController
withWKWebView(1)
as root view WKWebView(1)
has a hyperlink withtarget: _blank
parameter set- After tapping the link, I catch
WKUIDelegate
'swebView(_:didRequestNewWebView:)
and push anotherWKWebView(2)
ontoUINavigationController
WKWebView(2)
performs a request to server- Server responds with JavaScript message to
WKWebView(1)
- I never get the message, because
WKWebView(1)
is halted