UIWebview获取所选文本的范围并保存以供以后使用

UIWebview get range of selected text and save for later use

本文关键字:保存 范围 获取 文本 UIWebview      更新时间:2023-09-26

我使用以下java脚本函数从UIWebView获取所选文本的范围:

function getRangeForSelectedText() {
    var selection = window.getSelection(); 
    var range = selection.getRangeAt(0); 
}

我必须保存此范围以供以后使用(我想在用户稍后加载文档时使用此范围突出显示文本(。如何在目标 C 中保存 java 脚本对象(范围(?

除了给出范围之外,还有其他方法可以在 UIWebview 中突出显示文本吗?

看到那篇帖子http://blog.techno-barje.fr/post/2010/10/06/UIWebView-secrets-part3-How-to-properly-call-ObjectiveC-from-Javascript/

以及如何从Javascript调用Objective-C?

您可以使用脚本将一些字符串发送到您的 UIWebView

function sendURLToUIWebView(url) {
    var iframe = document.createElement("IFRAME");
    iframe.setAttribute("src", url);
    document.documentElement.appendChild(iframe);
    iframe.parentNode.removeChild(iframe);
 }

您的网址应该有特定的 schem f.e. myappcomand://

你可以用UIWebViewDelegate方法处理它(将一些对象设置为UIWebView的委托,即一些UIViewController(

- (BOOL)webView:(UIWebView *)aWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
 BOOL shouldLoad = YES;
    if ([request.URL.scheme isEqualToString:@"myappcomand"]) {
         shouldLoad = NO;
         // parse url string "request.URL" and extract your parameters to store them
    }
return shouldLoad;
}

你的JavaScript函数

function sendURLToUIWebView(url) {
    var iframe = document.createElement("IFRAME");
    iframe.setAttribute("src", url);
    document.documentElement.appendChild(iframe);
    iframe.parentNode.removeChild(iframe);
 }
function getRangeForSelectedText() {
    var selection = window.getSelection(); 
    var range = selection.getRangeAt(0);
    var url = "myappcomand://" + "range=" + range; // you should convert range to string 
    sendURLToUIWebView(url);
}

更新:

范围到字符串

range.toString().replace(/'s+/g, ' ').replace(/^'s+|'s+$/g, '')

或者只是var rangeText = window.getSelection().toString();

请参阅 range.toString(( 的奇怪行为

我遇到了同样的问题。我没有获得选定的范围,而是在 js 中使用下面的函数突出显示选定的文本,并在 UIWebView 中获取全文并在 sqlite 中替换它。

JS代码:

function highlight() {
    if (typeof window.getSelection != "undefined") {
        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 = "rgb(237,191,245)";
        span.style.color = "black";
        range.insertNode(span);
    } 
}

目标C:

- (void) highlightText
{
    NSString *highlightFunction = [NSString stringWithFormat:@"highlight()"];
    [detailedWebView stringByEvaluatingJavaScriptFromString:startSearch];
    NSString *highlightedString = [detailedWebView 
                         stringByEvaluatingJavaScriptFromString:@"document.documentElement.outerHTML"];
}

只需将旧的 html 字符串替换为突出显示的字符串即可。