RGS
RGS

Reputation: 4253

Highlight text in webview and save it

I have a webview that I display some html texts (I have them in assets). I'd like to allow users to highlight some parts of it.

I was thinking in some solutions:

  1. try to put the texts user hightlight in a shared pref and use:

    webview.findAllAsync(shared_pref_string);

    webview.setFindListener(new FindListener() {

         @Override
         public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
             // try to select the texts.
         }
     });
    

The problem I see is, user can select one word, like "what", and this code will select all "whats" the text has.

  1. Use javascript:

    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:block;background:#ffc570;\");"+
     "range.insertNode(span);}"+
     "</script> ";
    

    webView.loadUrl("javascript:highlightSelection()");

But this 2 solutions not seems nice to me, any other best way to do this and more modern?

Upvotes: 0

Views: 231

Answers (1)

Ebraheem bdarni
Ebraheem bdarni

Reputation: 11

this android library is implemented what you need:

https://github.com/FolioReader/FolioReader-Android

they are using this javascript library https://github.com/timdown/rangy, maybe this will make sense.

Upvotes: 1

Related Questions