I have certain text in the web view. I can select those text . I want to highlight those text but I have no idea how to do it. Anyone having any idea about it, please help! Thanx!
Asked
Active
Viewed 2,724 times
2 Answers
2
you need to run java script
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> ";
and
webView.loadUrl("javascript:highlightSelection()");
make sure you enabled javascript
WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);

Manohar
- 22,116
- 9
- 108
- 144
-
thanks. Can you explain me a bit more? this userSelection.rangeCount is this inbuilt function? can you explain this piece of code to me. Thanks in Advance – MagicWand Sep 01 '17 at 05:18
-
yes it will be inbuilt function. when ever you are loading data into webview add the string Highlightscript along with it . and when user clicks highlight button call `webView.loadUrl("javascript:highlightSelection()");` – Manohar Sep 01 '17 at 06:34
-
on longPress webview allows to select text. so this userselection.rangecount would know the starting and ending point of the user selection? Another thing is by on long press i am getting some of the default options like copy,share,search on web . Is there any way to add more options to it or disable these options.? – MagicWand Sep 01 '17 at 07:56
-
yes, see this https://stackoverflow.com/questions/22336903/use-a-custom-contextual-action-bar-for-webview-text-selection/22391169#22391169 – Manohar Sep 01 '17 at 07:58
-
@ManoharReddy is it possible to save what the user highlighted? So that the next time he opens the application, the text remains hightlight? – RGS Mar 30 '21 at 08:59
-
1@RGS check if this is helpful https://stackoverflow.com/questions/41670806/how-to-highlight-text-permanently-on-android-webview . – Manohar Mar 31 '21 at 06:29