1

I am using a webView to display text content, and I am trying to use javascript to highlight text that the user selects. This becomes possible when contentEditable = yes, but that also brings up the keyboard whenever the user taps on any text.

How can I have the contentEditable = yes, but not have the keyboard show up so that the text is editable?

EDIT: Here is the code I am using to do the highlighting

- (void)highlight {
     NSString *currentColor = [webView stringByEvaluatingJavaScriptFromString:@"document.queryCommandValue('backColor')"];
     if ([currentColor isEqualToString:@"rgb(255, 255, 0)"]) {
         [webView stringByEvaluatingJavaScriptFromString:@"document.execCommand('backColor', false, 'white')"];
     } else {
         [webView stringByEvaluatingJavaScriptFromString:@"document.execCommand('backColor', false, 'yellow')"];
     }
}

I found it on this tutorial.

Lizza
  • 2,769
  • 5
  • 39
  • 72

2 Answers2

2

You need to use the WebEditingDelegate that is part of the WebKitFramwork. Then you can do:

 -(BOOL)webView:(WebView *)shouldBeginEditingInDOMRange:(DOMRange *)range: {
     return NO;
  }

This is the documentation.

Mika
  • 5,807
  • 6
  • 38
  • 83
  • Looks to be exactly what I need, how do I use it though? Webkit isn't something that I can import, how do I sign up as the WebEditingDelegate? Thanks for the answer! – Lizza Feb 10 '14 at 16:58
  • Hmm, does it need to be on a subclass of UIWebView? Adding it on my viewController is generating build errors in Xcode. Thanks for your help. – Lizza Feb 10 '14 at 17:34
  • You need to install it. This is the link webkit.org/building/build.html. Sorry for the miss information I forgot. – Mika Feb 10 '14 at 17:37
  • So I will need to bundle WebKit with my app to prevent the keyboard from showing up? Seems a bit heavy :) – Lizza Feb 10 '14 at 17:40
0

So thanks to this post, I was able to come across a solution to this problem:

[self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('target').setAttribute('contentEditable','true')"];

if ([currentColor isEqualToString:@"rgb(255, 255, 0)"]) {
    [self.webView stringByEvaluatingJavaScriptFromString:@"document.execCommand('backColor', false, 'white')"];
} else {
    [self.webView stringByEvaluatingJavaScriptFromString:@"document.execCommand('backColor', false, 'yellow')"];
}

[self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('target').setAttribute('contentEditable','false')"];

I basically turn on editing only long enough to make a highlight in the webView, and then turn it back off right after I'm done. Probably not the most elegant solution, but the keyboard doesn't ever show up, and the highlighting works like a charm.

Community
  • 1
  • 1
Lizza
  • 2,769
  • 5
  • 39
  • 72