It's known to be difficult to get selected text in a WebView because WebView text selection is actually handled by a private class, WebTextView.
However, with the recently released Android 4.0 Design guidelines, there seems to be a glimmer of hope of achieving this through contextual action bars (CABs). It says:
Use CABs whenever you allow the user to select data via long press. You can control the action content of a CAB in order to insert the actions you would like the user to be able to perform.
Am I misinterpreting this? Is there a way to retrieve selected text from a WebView via a CAB?
After a long click and text selection mode begins, I can currently detect when the ActionMode
starts and modify the original copy/paste Menu
; however, I can't quite figure out how to actually retrieve the selected text.
You can't do that yet with the current API.
I filed a feature request for this - Issue 24841: WebView should allow applications to supply a custom Contextual Action Bar http://code.google.com/p/android/issues/detail?id=24841
Basically, WebView in 4.0 has hardcoded its own Contextual Action Bar (CAB). That CAB has a reference back to the WebView and with that reference, it can get the selected text. I'm not sure how you were able to detect the ActionMode starting and modify the menu, but if you were able to do all of that, then you are stuck because getSelection() is package-private currently. I filed that as a separate issue and linked it to the previous issue above.
You can use javascript to get the selected text: window.getSelection(), and use WebView's addJavascriptInterface function to return the result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With