我想在 UIWebView 中获取选定的单词。但有时我无法得到。这是我的代码。
我使用 javascript 来获取选定的单词。(getSelectedword.js)
var selectedText = "";
function getTextSelection() {
var text = window.getSelection();
selectedText = text.anchorNode.textContent.substr(text.anchorOffset, text.focusOffset - text.anchorOffset);
}
接着
-(void)showHeightlight
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"getSelectedword" ofType:@"js"];
NSError *error = nil;
NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
[webView stringByEvaluatingJavaScriptFromString:jsCode];
[webView stringByEvaluatingJavaScriptFromString:@"getTextSelection()"];
NSString *result = [webView stringByEvaluatingJavaScriptFromString:@"selectedText"];
NSLog(@"selected: %@", result);
}
如果我选择了单词并更改了范围,我无法获得选定的单词。