0

I have created an custom menu for WebView, one of the options I want to be able to do is copy. How can I get the selected text from WebView?

@Override
public void onActionModeStarted(ActionMode mode) {
    super.onActionModeStarted(mode);

    MenuInflater menuInflater = mode.getMenuInflater();
    Menu menu = mode.getMenu();

    menu.clear();
    menuInflater.inflate(R.menu.highlight, menu);


    menu.findItem(R.id.custom_one).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {

            ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("webView", val); //How to get the val?
            clipboard.setPrimaryClip(clip);
            return false;
        }
    });
}
Steven
  • 1,404
  • 2
  • 16
  • 39
Dim
  • 4,527
  • 15
  • 80
  • 139
  • 1
    [This](https://stackoverflow.com/questions/34804100/how-to-get-the-selected-text-of-webview-in-actionmode-override) might help. – ADM Feb 25 '18 at 12:06

1 Answers1

1

The selected text can be retrieved by using the evaluateJavascript method of the WebView to evaluate the following script: (function(){return window.getSelection().toString()})()

The result of the script is returned via the onReceiveValue method of the callback, more details are described in following post:

https://stackoverflow.com/a/44898840/378795

Livio
  • 530
  • 7
  • 14