1

Problem

You can select text in the WKWebView.

Desired Behaviour

You should not be able to select text in the webview at all.

What I've tried

  1. Loading NSString * jsCallBack = @"window.getSelection().removeAllRanges();"; using evaluateJavaScript:completionHandler:
  2. doing the above using "document.documentElement.style.webkitUserSelect='none'"
  3. webView.configuration.selectionGranularity = nil; <-- This one doesn't make sense as selectionGranularity can only take two predefined values, but it was worth a try.
  4. Tried looking for a solution inside the storyboard, couldn't find a solution that wouldn't disable user interactions.

What I can not do

Changing the HTML/CSS code is not an option at this time, if I could change it this answer would probably work.

Community
  • 1
  • 1
Spartacus9
  • 164
  • 2
  • 18
  • I shared some details on inner details of how selection works internally in `WKWebView` in my answer here: https://stackoverflow.com/a/49437716/5329717 I'll have a proper look at your case eventually. – Kamil.S Mar 23 '18 at 09:56

1 Answers1

0

Semi private gray area solution relying on private web views hierarchy and its tap gestures. As a bonus doesn't rely on private class & method symbols, but if order of tap gestures would change it would break.

@import WebKit;
@interface ViewController ()

@property(null_resettable, nonatomic,strong) WKWebView *view;
@end

@implementation ViewController

@dynamic view;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view = [WKWebView new];

    for (UIView *view in self.view.subviews) {
        for (UIView *innerView in view.subviews) {
            if (innerView.gestureRecognizers.count > 0) {
                NSMutableArray<UIGestureRecognizer*> *gestureRecognizers = [innerView.gestureRecognizers mutableCopy];
                [gestureRecognizers removeObjectAtIndex:0];
                innerView.gestureRecognizers = [gestureRecognizers copy];
            }
        }
    }

    [self.view loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://stackoverflow.com/questions/43227437/how-to-disable-text-selection-wkwebview-programatically"]]];
}
@end
Kamil.S
  • 4,777
  • 2
  • 19
  • 46