Search code examples
androidwebviewhighlight

Highlight the selected text in webview. [Android]


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!


Solution

  • 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);