Skip to content

Custom delegate on WKWebView is replaced by mock when snapshotting #440

Closed
@teameh

Description

@teameh

When a user sets a custom navigation delegate on a WKWebView and makes a snapshot of a view containing this web view, the navigation delegate may be replaced by a stub that makes sure the snapshotting lib knows when to snapshot the web view. This works great when users don't implement a custom WKNavigationDelegate themselves. But when a user implements a custom delegate themselves this fails.

Consider for example a custom delegate that limits the web view to github.com and opens the browser as soon as the user taps on a link outside of github.com

class GithubNavigationDelegate: NSObject, WKNavigationDelegate {
  override init() { }

  public func webView(
    _ webView: WKWebView,
    decidePolicyFor navigationAction: WKNavigationAction,
    decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
  ) {
    // limit to webpages on to github.com
    guard navigationAction.request.url?.host == "github.com" else {
      decisionHandler(.cancel)
      // Warn user and open url in browser instead
      return
    }

    decisionHandler(.allow)
  }
}


webview.navigationDelegate = GithubNavigationDelegate()

This can't be snapshot tested at the moment because the delegate is removed as soon as a snapshot is made.

I think this could be fixed by retaining the original delegate, implementing all the possible delegate methods and forwarding all the calls to the original delegate. I'll see if I can draft up a PR. Please let me know if you think of another way of dealing with this issue.

Finally, many thanks for all the work on this great lib 👏🏼 so far, hopefully I can contribute back a bit.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions