get selected text from a uiwebview Xcode

蓝咒 提交于 2021-02-07 03:24:55

问题


I have a UIWebView that loads text from an htmlString. I need when the user selects a part of the text and presses a button, i will be capable of extracting it in order to use it elsewhere, so i am using this code :

  // 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];

Along with 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);
}

I always get nothing as a result ... The alert view shows nothing...What's the problem with this code ? Any help ? Any ideas ? It will be really appreciated.


回答1:


The solution was actually pretty simple and no need for all the above code! For any future users just use:

 NSString *textToSpeech = [WebV2 stringByEvaluatingJavaScriptFromString: @"window.getSelection().toString()"];
 NSLog(@" -**-*--****-*---**--*-* This is the new select text %@",[WebV2 stringByEvaluatingJavaScriptFromString: @"window.getSelection().toString()"] );



回答2:


NSString *theSelectedText = [self.webView stringByEvaluatingJavaScriptFromString:@"window.getSelection().toString()"];

This will pass your selection to the string variable.



来源:https://stackoverflow.com/questions/13285589/get-selected-text-from-a-uiwebview-xcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!