iPhone Development: Grabbing selected/highlighted text on UIWebView

让人想犯罪 __ 提交于 2019-11-30 07:16:01

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!