2

I am working on an android application,which has a WebView. in this web view when i select the html text and perform any action the window.getSelection() is coming null.

One javascript method window.getSelection() doesn't return the selected text from WebView every time. Many developers raised issues to Google for this but no solutions. https://issuetracker.google.com/issues/36925404

I tried all possible option to get the selection object like

window.getSelection(); window.doument.getSelection(); document.getSelection(); EReader.Selection.Range.getCurrentRange();

Do you have any suggestions?

Phantômaxx
  • 37,352
  • 21
  • 80
  • 110

1 Answers1

-1

With Android API >= 19 you can use evaluateJavascript:

webview.evaluateJavascript("(function(){return window.getSelection().toString()})()",
new ValueCallback<String>()
{
    @Override
    public void onReceiveValue(String value)
    {
        Log.v(TAG, "SELECTION:" + value);
    }
});

On older builds, you should call via webview.loadUrl passing the same thing:

webview.loadUrl("javascript:js.callback(window.getSelection().toString())");

where js is the attached javascript interface:

webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new WebAppInterface(), "js");

and

public class WebAppInterface
{
    @JavascriptInterface
    public void callback(String value)
    {
        Log.v(TAG, "SELECTION:" + value);
    }
}

Reference

Jitesh Prajapati
  • 2,661
  • 4
  • 28
  • 47