akshayhallur
akshayhallur

Reputation: 101

How to get Selected Text in WebView Android

I am developing an application in which I need the get the selected text.

I have a custom contextual action bar, that shows up when user selects a text in webview. I want to get highlighted text under selection handlers, on click of my action bar button.

Question was previously asked, How to get the selected text in android webview.

But had no solution.

I am trying something like myWebView.getSelection()

Upvotes: 10

Views: 4856

Answers (2)

SJX
SJX

Reputation: 1239

Addition Mahendra Liya answer:
Also for API >=19 you need to enable JavaScript:

WebSettings settings = yourWebview.getSettings();
settings.setJavaScriptEnabled(true);

Upvotes: 0

Mahendra Liya
Mahendra Liya

Reputation: 13218

I posted an answer to a similar question. Sharing it here for quick access to the answer.

For API >= 19 you can use evaluateJavascript

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

For API < 19 you can use evaluateJavascript you use the loadUrl method like below:

mWebview.getSettings().setJavaScriptEnabled(true);
mWebview.addJavascriptInterface(new JavaScriptInterface(), "javascriptinterface");

Then when you want to get the selection use the following:

mWebview.loadUrl("javascript:javascriptinterface.callback(window.getSelection().toString())");

And define a WebAppInterface class as below:

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

Upvotes: 9

Related Questions