Skip to content

Commit

Permalink
Fix WKWebView retain cycles in Reader
Browse files Browse the repository at this point in the history
  • Loading branch information
kean committed Jan 29, 2025
1 parent e1449ab commit c19bb22
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ class WebCommentContentRenderer: NSObject, CommentContentRenderer {
webView.scrollView.showsVerticalScrollIndicator = false
webView.scrollView.backgroundColor = .clear
webView.configuration.allowsInlineMediaPlayback = true
webView.configuration.userContentController.add(self, name: "eventHandler")

// - warning: It retains the handler. It can't be `self`.
webView.configuration.userContentController.add(ReaderWebViewMessageHandler(), name: "eventHandler")
}

func render() -> UIView {
Expand Down Expand Up @@ -112,20 +114,6 @@ extension WebCommentContentRenderer: WKNavigationDelegate {
}
}

// MARK: - WKScriptMessageHandler

extension WebCommentContentRenderer: WKScriptMessageHandler {

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
guard let body = message.body as? String,
let event = ReaderWebView.EventMessage(rawValue: body)?.analyticEvent else {
return
}
WPAnalytics.track(event)
}

}

// MARK: - Private Methods

private extension WebCommentContentRenderer {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ class ReaderWebView: WKWebView {
isInspectable = true
}

configuration.userContentController.add(self, name: "eventHandler")
// - warning: It retains the handler. It can't be `self`.
configuration.userContentController.add(ReaderWebViewMessageHandler(), name: "eventHandler")
}

/// Loads a HTML content into the webview and apply styles
Expand Down Expand Up @@ -311,8 +312,7 @@ class ReaderWebView: WKWebView {
}
}

extension ReaderWebView: WKScriptMessageHandler {

final class ReaderWebViewMessageHandler: NSObject, WKScriptMessageHandler {
enum EventMessage: String {
case articleTextHighlighted
case articleTextCopied
Expand Down Expand Up @@ -342,5 +342,4 @@ extension ReaderWebView: WKScriptMessageHandler {
}
WPAnalytics.track(event)
}

}

0 comments on commit c19bb22

Please sign in to comment.