Craig Craig - 29 days ago 18
iOS Question

How to capture taps ignored by WKWebView

I have a view that contains a

WKWebView
. My html content is generated by my app, so I know for sure it is never wider than the screen, so I'm using
UIGestureRecognizer
s on its superview to react to left and right swipes. That works great.

I would also like to see any tap that is not on a link so I can decide what I might want to do with those. It appears that
WKWebView
sucks up all taps. I tried asking it for its array of gesture recognizers so that I could set up some cooperation with them, but I get nil no matter when I ask (i.e. after creating the
WKWebView
, after loading it with my HTML file, and when notified that it has finished loading). This makes sense if
WKWebView
isn't using the
UIGestureRecognizer
mechanism but instead is just watching for taps and not passing them along if it turns out it is not interested in them.

Any ideas for getting access to
WKWebView
's unwanted taps?

Answer

Turns out the solution to this is to turn the problem inside out. I put a transparent UIView over the WKWebView and attached several UIGestureRecognizers to my transparent view. I use JavaScript calls to react to pan gestures. When a tap is recognized on my transparent view, I query the DOM to see if it is a link and if not, I can do whatever I want with it. Another benefit is that I get to handle long press, which is something I wanted to do instead of letting WKWebView do its baked-in, unchangeable behavior. This works really well.

Comments