Having an app with a webview, I have been struggling to retrieve user-selected text from the body of the webview. While iOS handles this task seamlessly, Android falls short in this aspect, posing a challenge for me. Despite scouring various resources, including websites and Google, I couldn't find a solution. Fortunately, my app features a javascript interface that allows communication with a script loaded into the webview. My initial idea was to utilize javascript to extract the text from the webview. In Chrome, I managed to achieve this using the following javascript snippet:
window.getSelection.toString();
Currently, I have a button triggering a function in my js file, executing the above command and passing the results to a method in my javascript interface. The information is then displayed through a toast message. However, after selecting text and clicking the button, the toast message only shows:
javascript returned:
instead of:
javascript returned: <my selected text>
Upon removing the '.toString();' part from the javascript command and attempting to select text again before pressing the button, the message displayed reads:
javascript returned: undefined
This issue leaves me puzzled. Here's the relevant code snippet showing the javascript function being called:
myNameSpace.getTextSelection = function()
{
var str;
if (window.getSelection){
str = window.getSelection().toString();
} else {
str = 'does not';
}
window.myJSHandler.getSelectedText(str);
};
Additionally, here's the Java function being invoked:
public void getSelectedText(String text)
{
String str = "function called. it returned: " + text;
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
}