I have a WebView class and I want to select specific text from the rendered html code in a specific region.
Method: public static void selectTextInWebView(WebView webView, int startIndex, int endIndex)
I tried to write a JS code but it doesn’t work.
String script = "function selectRange(start, end) {" +
" var range = document.createRange();" +
" var selection = window.getSelection();" +
" var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null, false);" +
" var charCount = 0;" +
" var startNode, endNode, startOffset, endOffset;" +
" while (walker.nextNode()) {" +
" var node = walker.currentNode;" +
" var nextCharCount = charCount + node.length;" +
" if (!startNode && nextCharCount > start) {" +
" startNode = node;" +
" startOffset = start - charCount;" +
" }" +
" if (nextCharCount >= end) {" +
" endNode = node;" +
" endOffset = end - charCount;" +
" break;" +
" }" +
" charCount = nextCharCount;" +
" }" +
" if (startNode && endNode) {" +
" range.setStart(startNode, startOffset);" +
" range.setEnd(endNode, endOffset);" +
" selection.removeAllRanges();" +
" selection.addRange(range);" +
" }" +
"}" +
"selectRange(" + startIndex + ", " + endIndex + ");";
webView.getEngine().executeScript(script);