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

2 Answers2

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
  • 5,205
  • 2
  • 22
  • 51
0
**// add gesture on viewDidLoad**
override func viewDidLoad() 
{
    super.viewDidLoad()
    let longPress:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: nil, action: nil)
    longPress.minimumPressDuration = 0.3
    webView.addGestureRecognizer(longPress)
}

**//also inherit the UIGestureRecognizerDelegate**

class ViewController: UIViewController, UIGestureRecognizerDelegate {
}
Albin KJ
  • 1
  • 3
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 16 '23 at 11:52