WKWebKit javascript execution when not attached to a view hierarchy

前端 未结 2 1127
日久生厌
日久生厌 2020-12-08 04:27

I want to switch to WKWebView from UIWebView. In my code, the web view instance is created offscreen (without attaching to the view hierarchy) and

2条回答
  •  失恋的感觉
    2020-12-08 04:41

    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

提交回复
热议问题