无法在uiwebview中获取所选单词

时间:2011-12-10 06:51:03

标签: javascript ios uiwebview selected words

我想在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);

}

如果我选择了单词并更改了范围,我就无法获得所选单词。

1 个答案:

答案 0 :(得分:1)

我改变了我的核心。没关系。

getSelectedword.js

function getTextSelection() {
var text = window.getSelection();
return text.toString();
}

然后

-(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];
 NSString *result  = [webView stringByEvaluatingJavaScriptFromString:@"getTextSelection()"];
 NSLog(@"selected: %@", result);
}