我有一個UIWebView
,它從htmlString
加載文本。 我需要當用戶選擇文本的一部分,按下一個按鈕,我將能夠爲其他地方使用它提取它,所以我用這個代碼:從uiwebview中獲取選定的文本Xcode
// The JS File
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"HighlightedString" ofType:@"js" inDirectory:@""];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSString *jsString = [[NSMutableString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
[WebV2 stringByEvaluatingJavaScriptFromString:jsString];
// The JS Function
NSString *startSearch = [NSString stringWithFormat:@"getHighlightedString()"];
[WebV2 stringByEvaluatingJavaScriptFromString:startSearch];
NSString *selectedText = [NSString stringWithFormat:@"selectedText"];
NSString * highlightedString = [WebV2 stringByEvaluatingJavaScriptFromString:selectedText];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Highlighted String"
message:highlightedString
delegate:nil
cancelButtonTitle:@"Oh Yeah"
otherButtonTitles:nil];
[alert show];
隨着HighlightedString.js
:
/*!
------------------------------------------------------------------------
// Search Highlighted String
------------------------------------------------------------------------
*/
var selectedText = "";
function getHighlightedString() {
var text = window.getSelection();
selectedText = text.anchorNode.textContent.substr(text.anchorOffset, text.focusOffset - text.anchorOffset);
}
// ...
function stylizeHighlightedString() {
var range = window.getSelection().getRangeAt(0);
var selectionContents = range.extractContents();
var span = document.createElement("span");
span.appendChild(selectionContents);
span.setAttribute("class","uiWebviewHighlight");
span.style.backgroundColor = "black";
span.style.color = "white";
range.insertNode(span);
}
// helper function, recursively removes the highlights in elements and their childs
function uiWebview_RemoveAllHighlightsForElement(element) {
if (element) {
if (element.nodeType == 1) {
if (element.getAttribute("class") == "uiWebviewHighlight") {
var text = element.removeChild(element.firstChild);
element.parentNode.insertBefore(text,element);
element.parentNode.removeChild(element);
return true;
} else {
var normalize = false;
for (var i=element.childNodes.length-1; i>=0; i--) {
if (uiWebview_RemoveAllHighlightsForElement(element.childNodes[i])) {
normalize = true;
}
}
if (normalize) {
element.normalize();
}
}
}
}
return false;
}
// the main entry point to remove the highlights
function uiWebview_RemoveAllHighlights() {
selectedText = "";
uiWebview_RemoveAllHighlightsForElement(document.body);
}
我總是沒有得到任何結果......警報視圖沒有顯示任何內容......這段代碼有什麼問題?任何幫助?有任何想法嗎 ?這將非常感激。
謝謝你的貢獻...但我在一年前得到了答案!這裏是一個讚許:) –
如何獲取webview內容中選定文本的開始和結束範圍 –