John Doe
John Doe

Reputation: 2501

WKWebView is not reclaiming after closing the NSWindow

I have called window.close() on an NSWindowController. I am getting the window controller deinit call. But the NSViewController associated with the window is not reclaiming. The deinit of the view controller is not getting called.

The window controller loads a WKWebView. I then set the html content to empty before invoking close. I have set nil for all delegate in deinit and delegate are all weak.

The activity monitor shows the Web Content process.

Web Content Process

I have code like:

class WebKitViewController: NSViewController {
    var webView: WKWebView?
    private lazy var msgService: WebViewMessageService? = {
        let s = WebViewMessageService()
        s.delegate = self
        return s
    }()
    weak var delegate: WebKitDelegate?
    // ...

    func initWebView() {
        let webView = WKWebView(frame: CGRect.zero, configuration: self.initWebKitConfig())
        webView.navigationDelegate = self
        webView.uiDelegate = self
        self.view.addSubview(webView)
        // ...
    }
}

How to reclaim the memory and fully exit the WindowController with a WKWebView based NSWindowController?


The close function in the WebKitViewController is as below.

func closeWindow() {
    DispatchQueue.main.async {
        self.webView?.uiDelegate = nil
        self.webView?.navigationDelegate = nil
        self.msgService?.delegate = nil
        self.webView?.removeFromSuperview()
        if let window = self.view.window, let wc = window.windowController as? WebKitWindowController {
            Log.debug("Closing window \(wc.windowId)")
            self.webView?.loadHTMLString("", baseURL: nil)
            self.delegate?.closeWindow(windowId: wc.windowId)
        }
    }
}

Upvotes: 1

Views: 628

Answers (1)

AVerguno
AVerguno

Reputation: 1377

It seems like a well-known bug of WKScriptMessageHandler. Here is similar question by this link: Memory leak when using WKScriptMessageHandler

What can you do to avoid leaks:

Call removeScriptMessageHandlerForName() when you're closing your window.

Upvotes: 1

Related Questions