如何在iOS中的WebView内容中获得突出显示的文本范围?

时间:2016-03-03 06:06:23

标签: ios objective-c nsstring nsrange

将此代码应用于.js文件

var selectedText = "";
function getHighlightedString()
{
  var text = document.getSelection();
  startIndex = text.anchorOffset;
  endIndex = text.focusOffset;
  selectedText = text.anchorNode.textContent.substr(startIndex,endIndex - text.anchorOffset);
  var rangeText = document.getSelection().toString();
}
function highlight() {
 if (typeof window.getSelection != "undefined") {
  var range = document.getSelection().getRangeAt(0);
  var selectionContents = range.extractContents();
  var span = document.createElement("span");
  span.appendChild(selectionContents);
  span.setAttribute("class","uiWebviewHighlight");
  span.style.backgroundColor = "rgb(237,191,245)";
  span.style.color = "orange";
  range.insertNode(span);
 }
}

我正在使用此代码突出显示文字。

NSString *filePath  = [[NSBundle mainBundle] pathForResource:@"first" ofType:@"js" inDirectory:@""];
NSData *fileData    = [NSData dataWithContentsOfFile:filePath];
NSString *jsString  = [[NSMutableString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
[webView_Detail stringByEvaluatingJavaScriptFromString:jsString];

NSString *highlightFunction = [NSString stringWithFormat:@"highlight()"];
[webView_Detail stringByEvaluatingJavaScriptFromString:highlightFunction];
highlightedString = [webView_Detail                                     stringByEvaluatingJavaScriptFromString:@"document.documentElement.outerHTML"];

我坚持要获得文本范围。它我必须发送到服务器。但我无法获得选定的文本范围。 请帮我。

1 个答案:

答案 0 :(得分:0)

尝试以下

NSString * strJS = @"window.getSelection().toString()";
NSString * strSelectedText = [self.webView stringByEvaluatingJavaScriptFromString:strJS];
NSString *plainText = [self.webView stringByEvaluatingJavaScriptFromString:@"document.body.textContent"];
NSRange * rangeOfString = [plainText rangeOfString:strSelectedText];

您也可以尝试以下替代

NSString *plainText = [self.webView stringByEvaluatingJavaScriptFromString: @"document.body.innerText"];

如果找到所选文本的多个匹配项,请参阅以下链接以查找所有出现的范围。

Find all locations of substring in NSString (not just first)