Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting selected text in a WebView via a contextual action bar

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.

like image 202
octopi Avatar asked Jan 13 '12 19:01

octopi


2 Answers

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.

like image 85
louielouie Avatar answered Nov 18 '22 19:11

louielouie


You can use javascript to get the selected text: window.getSelection(), and use WebView's addJavascriptInterface function to return the result.

like image 1
Rayman Zhang Avatar answered Nov 18 '22 17:11

Rayman Zhang