Greetings,
Please kindly advice on how possibly I can get the selected text on UIWebVIew.
I went on to search on how to deal with selected/highlighted text and found the following:
Selection and Menu Management
To copy or cut something in a view,
that “something” must be selected. It
can be a range of text, an image, a
URL, a color, or any other
representation of data, including
custom objects. To implement
copy-and-paste behavior in your custom
view, you must manage the selection of
objects in that view yourself. If the
user selects an object in the view by
making a certain touch gesture (for
example, a double-tap) you must handle
that event, internally record the
selection (and deselect any previous
selection), and perhaps visually
indicate the new selection in the
view. If it is possible for users to
select multiple objects in your view
for copy-cut-paste operations, you
must implement that multiple-selection
behavior.
And that's where I got lost. "...record the selection" - I'm not even sure how to represent a selection let alone recording it.
Any help is very much appreciated. ^^ Cheers!
Kind regards,
oonoo
You can use stringByEvaulatingJavaScriptFromString to get the currently selected text in a UIWebView.
NSString *selection = [self.webView stringByEvaluatingJavaScriptFromString:@"window.getSelection().toString()"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Selected Text" message:selection delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil];
[alert show];
[alert release], alert = nil;
Take a look at using window.getSelection() in JavaScript. It will allow you to get the current text selection which you could then store in a global variable and access that variable via the stringByEvaluatingJavaScriptFromString method on UIWebView. Unfortunately, I don't know of a way in iOS JavaScript to identify when the text selection has changed so instead use an interval to continuously check for that. I have actually done all this so I know it can work. In terms of storing the text selection ranges for later use as well as applying styles I would look into a JavaScript library named rangy. I found it to be incredibly useful in creating highlighting jQuery plugin (that works on both the desktop and on iOS - not for Android though).