1

I'm loading my Webview from a text string, like so:

String encodedHtml = Base64.encodeToString(unencodedHtml.getBytes(), Base64.NO_PADDING);
webview.loadData(encodedHtml, "text/html", "base64");
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);

I'd like to add a color Highlight option to the Menu, when the user long press a word. I've searched many other similar questions on StackOverflow without success. Your help with some sample code would be much appreciated. Thanks in advance!

UPDATE: I'm using this script to highlight:

public static String HighlightScript = "<script language=\"javascript\">" +
        "function highlightSelection(){" +
        "var userSelection = window.getSelection();" +
        "for(var i = 0; i < userSelection.rangeCount; i++)"
        + "  highlightRange(userSelection.getRangeAt(i));" +
        "}" +
        "function highlightRange(range){"+
        "span = document.createElement(\"span\");"+
        "span.appendChild(range.extractContents());"+
        "span.setAttribute(\"style\",\"display:inline;background:#ffc570;\");"+
        "range.insertNode(span);}"+
        "</script> ";
neowinston
  • 7,584
  • 10
  • 52
  • 83

1 Answers1

1

based on this Calculate Position of selected text javascript/JQuery? call WebView's evulatejavascript to get start end values

objWebView.evaluateJavascript("(function(){var start = 0, end = 0;\n" +
                                        "    var sel, range, priorRange;\n" +
                                        "    if (typeof window.getSelection != \"undefined\") {\n" +
                                        "        range = window.getSelection().getRangeAt(0);\n" +
                                        "        priorRange = range.cloneRange();\n" +
                                        "        priorRange.selectNodeContents(document.body);\n" +
                                        "        priorRange.setEnd(range.startContainer, range.startOffset);\n" +
                                        "        start = priorRange.toString().length;\n" +
                                        "        end = start + range.toString().length;\n" +
                                        "    } else if (typeof document.selection != \"undefined\" &&\n" +
                                        "            (sel = document.selection).type != \"Control\") {\n" +
                                        "        range = sel.createRange();\n" +
                                        "        priorRange = document.body.createTextRange();\n" +
                                        "        priorRange.moveToElementText(document.body);\n" +
                                        "        priorRange.setEndPoint(\"EndToStart\", range);\n" +
                                        "        start = priorRange.text.length;\n" +
                                        "        end = start + range.text.length;\n" +
                                        "    }\n" +
                                        "        console.log(\"Selection starts at: \" + start);\n" +
                                        "        console.log(\"Selection ends at: \" + end);\n" +
    
    
                                        "    return {\n" +
                                        "        start: start,\n" +
                                        "        end: end\n" +
                                        "    };})()",
                                new ValueCallback<String>()
                                {
                                    @Override
                                    public void onReceiveValue(String value)
                                    {
                                        Log.v(TAG, "Webview selected text: " + value);
                                    }
                                });

Once you have saved range values in database. Call the same method to highlight ( works only after WebView's is finished loading the page

    objWebView.loadDataWithBaseURL(null, yourstringobject, "text/html; charset=UTF-8", "UTF-8",
                        null);
                objWebView.post(new Runnable() {
                    @Override
                    public void run() {
     //here you can have logic to fetch the data from database and loop to update                   
objWebView.evaluateJavascript("javascript:selectAndHighlightRange('Amod', 250, 274)", null);
                    }
            });
Amod Gokhale
  • 2,346
  • 4
  • 17
  • 32
  • It works great, Amod! Thanks a lot for the code! Now, there is just one thing that I need your help with. I'll save this range value in a local SQLite database to retrieve it later. After retrieving the range, how do I highlight it back on the text? Again, thanks for help! – neowinston Jun 17 '21 at 15:21
  • I've updated my question with the script I'm using to highlight. I'm just not sure how to pass the "range" object. Thanks for your help! – neowinston Jun 17 '21 at 17:11
  • @neowinston looks like method you written highlight whatever user has selected ( windows.selection). That method needs to be updated to take input parameter . I have used this https://stackoverflow.com/questions/6240139/highlight-text-range-using-javascript/6242538#6242538 and works fine. i'm not really sure how to update for your method. I guess that should be a separate question specific to jscript – Amod Gokhale Jun 17 '21 at 17:27
  • 1
    Thanks! You helped me a lot and I will keep researching on how to highlight it again. – neowinston Jun 17 '21 at 17:36
  • @neowinston - welcome.. do update your question if you find any better/easy alternative – Amod Gokhale Jun 17 '21 at 17:51