Reputation: 81
Applied this code in .js file
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);
}
}
And I'm using this code for highlighting the text.
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"];
I stuck for getting the text range. it i have to send to server.but i couldn't able to get selected text range. Please help me.
Upvotes: 0
Views: 895
Reputation: 6342
Try Following
NSString * strJS = @"window.getSelection().toString()";
NSString * strSelectedText = [self.webView stringByEvaluatingJavaScriptFromString:strJS];
NSString *plainText = [self.webView stringByEvaluatingJavaScriptFromString:@"document.body.textContent"];
NSRange * rangeOfString = [plainText rangeOfString:strSelectedText];
You can try following alternate also
NSString *plainText = [self.webView stringByEvaluatingJavaScriptFromString: @"document.body.innerText"];
If there are multiple matches found for selected text, please refer following link to find all ranges of occurrence.
Find all locations of substring in NSString (not just first)
Upvotes: 1