How to get selected text in Android WebView

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

I have a custom contextual action bar that appears when the user selects text in webview. I want to select the selected text in the selection handlers by clicking on the action bar button.

The question was previously asked, How to get selected text in an Android web browser.

But there was no solution.

I am trying something like myWebView.getSelection ()

+6
source share
1 answer

I sent an answer to a similar question. Separate 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, as shown 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 the WebAppInterface class as shown below:

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

Source: https://habr.com/ru/post/981931/


All Articles