IPhone Development: Grabbing selected/highlighted text on UIWebView

iphoneselectionuiwebview

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

Best Answer

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;
Related Topic